Is it possibly to use global variables in Handlebars conditionals? I'm writing an app that lists a lot of objects, and I want users to be able to control which details are listed. For example, displaying only first names in a list of people, like so:
<ul>
{{#each people}}
<li>
<p>{{firstName}}</p>
{{#if displayLastnames}}
<p>{{lastName}}</p>
{{/if}}
</li>
{{/each}}
</ul>
I don't want to actually modify the data (for example, by removing the lastName attribute and doing {{#if lastName}}
).
Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope.
Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces.
You can also register a global helper named 'displayLastnames' and use it in a if :
Handlebars.registerHelper('displayLastnames', function(block) {
return displayLastnames; //just return global variable value
});
and just use it as in your sample :
{{#if displayLastnames}}
<p>{{lastName}}</p>
{{/if}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With