Search code examples
backbone.jshandlebars.js

Calling a separate object as the context for a Handlebars Partial


So I have a HBS template that I am rendering using a backbone model. I want to create a set of partials for UI components that I can call with a different object to generate markup so:

<div class="device">
  This is my device default name: {{ defaultName }} <br/>
  This is my device current state: {{ currentState }} <br/>
  This is my device last state: {{ lastState }}
    {{> options}}
</div>

and the partial is:

{{#each options}}
<span data-value="{{value}}">Label: </span>{{label}} <br/>
{{/each}}

I want everything in the main template to use the model as the context and the partial to use a different object that I create in my view. Im trying to avoid having these options be married to my model code, yuck.

Update I did a little work around which is okay with $.extend

var data = $.extend({}, this.model.toJSON(), this.uiOptions);
this.$el.html(this.template(data));

Solution

  • One of the neatest ways to do this is to have two top level objects and to use the with helper in the first template

    Handlebars.compile(templateFile)({model:modelObj,other:OtherObj})
    

    and the template

    <div class="device">
        {{#with model}}
        This is my device default name: {{ defaultName }} <br/>
        This is my device current state: {{ currentState }} <br/>
        This is my device last state: {{ lastState }}
        {{/with}}
        {{#with other}}
        {{> options}}
        {{/with}}
    </div>