Daniel Buckmaster
Daniel Buckmaster

Reputation: 7186

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

Upvotes: 11

Views: 22659

Answers (2)

mu is too short
mu is too short

Reputation: 434615

Handlebars namespaces the variables so you can't directly access global variables. Probably the easiest thing to do is to add your own helper, something simple like this:

Handlebars.registerHelper('if_displayLastnames', function(block) {
    if(displayLastnames)
        return block.fn(this);
    else
        return block.inverse(this);
});

and then in your template:

{{#if_displayLastnames}}
<p>{{lastName}}</p>
{{/if_displayLastnames}}

You'd probably want to put your "global" variables in their own namespace of course.

Demo: http://jsfiddle.net/ambiguous/Y34b4/

Upvotes: 11

Alban Lecocq
Alban Lecocq

Reputation: 329

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

Upvotes: 18

Related Questions