Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables in Handlebars if blocks

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}}).

like image 452
Daniel Buckmaster Avatar asked Aug 03 '12 06:08

Daniel Buckmaster


People also ask

Are global variables in JavaScript bad?

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.

Can you use handlebars in JavaScript?

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.


1 Answers

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}}
like image 177
Alban Lecocq Avatar answered Sep 23 '22 08:09

Alban Lecocq