Javascript – Passing variables through handlebars partial

handlebars.jshtmljavascripttemplating

I'm currently dealing with handlebars.js in an express.js application. To keep things modular, I split all my templates in partials.

My problem: I couldn't find a way to pass variables through an partial invocation. Let's say I have a partial which looks like this:

<div id=myPartial>
    <h1>Headline<h1>
    <p>Lorem ipsum</p>
</div>

Let's assume I registered this partial with the name 'myPartial'. In another template I can then say something like:

<section>
    {{> myPartial}}
</section>

This works fine, the partial will be rendered as expected and I'm a happy developer. But what I now need, is a way to pass different variables throught this invocation, to check within a partial for example, if a headline is given or not. Something like:

<div id=myPartial>
    {{#if headline}}
    <h1>{{headline}}</h1>
    {{/if}}
    <p>Lorem Ipsum</p>
</div>

And the invokation should look something like this:

<section>
    {{> myPartial|'headline':'Headline'}}
</section>

or so.

I know, that I'm able to define all the data I need, before I render a template. But I need a way to do it like just explained. Is there a possible way?

Best Answer

Handlebars partials take a second parameter which becomes the context for the partial:

{{> person this}}

In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:

{{> person headline='Headline'}}

You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32