Search code examples
javascripthandlebars.js

styling variables not applied - handlebars


I am not sure how to properly apply css to handlebars. Hence I have created the helper function in js file to set the variable and while using those variables (contains style attributes and values) the style is not applied. Is there anything missing

Helper function:

handlebars.registerHelper("setVar", function(varName, varValue, options) {
  options.data.root[varName] = varValue;
});

Inside the handlebars file:

<script id="template" type="text/x-handlebars-template"></script>

{{setVar "tableStyling" "width: 100%;border: 1px solid lightgrey;border-collapse: collapse;"}}
{{setVar "thStyling" "border: 1px solid lightgrey;border-collapse: collapse;padding: 2px 4px;"}}
{{setVar "tdStyling" "border: 1px solid lightgrey;border-collapse: collapse;padding: 2px 4px;"}}
<table style={{tableStyling}}>
    <thead>
        <th style={{thStyling}}>Card Title</th>
        <th style={{thStyling}}>Expiry date</th>
        <th style={{thStyling}}>Target Url</th>
        <th style={{thStyling}}>Content Type</th>
        <th style={{thStyling}}>Entry Url</th>
    </thead>
    {{#each this}}
    <tr>
        <td style={{../tdStyling}}>{{cardTitle}}</td>
        <td style={{../tdStyling}}>{{expiryDate}}</td>
        <td style={{../tdStyling}}>{{targetUrl}}</td>
        <td style={{../tdStyling}}>{{type}}</td>
        <td style={{../tdStyling}}>{{contentfulUrl}}</td>
    </tr>
    {{/each}}
</table>
</script>

Solution

  • I reckon you are missing the quotes around the style property .

    Adding quotes to the table style <table style="{{tableStyling}}"> fixed the issue for me.

    There is an excellent site http://tryhandlebarsjs.com/ where you can try out your templates and helpers.

    Hope this helps