简体   繁体   中英

Add properties to context when rendering partial in Handlebars.js

Is it possible to add properties to context when rendering a partial template with handlebars.js?

{{> MyTemplate { X: Y }}}

I have a shared template that I need to insert some values to, depending on from which "master" template it is used.

You can't do this directly inside the call to the partial, no. But you can pass context into a partial, provided you already have it available in the wrapping context.

In order to "embed" data in a context, you can use a helper that sets a private variable, like so:

<div>
  {{makeVar 'mode' 33}}
  <span>mode: {{@mode}}</span><!-- will return mode: 33 -->
</div>

Then, by passing something dynamic from context into the makeVar helper, you can compute a value for @mode which will then be added into the current context.

You could also modify the context itself, or merge the context with computed data on the fly. ( Be careful: doing it that way affects downstream users of the context as well.)

So, you could call the partial like this, and let the wrapping context set @mode accordingly.

<div>
  {{> myPartial .}}<!-- inside partial, @mode is accessible, along with context -->
</div>

See: http://jsfiddle.net/mcw0933/Cy64X/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM