Alex Rivera | Logout

Global variables in Handlebars if blocks

Asked 2012-08-03T06:35:50.667
11

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

Edit
Report

1 Answer

11

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/

answered 2012-08-03T06:52:45.127

Your Answer