Handlebars.js: Assign variables in template

Created on 29 Mar 2013  ·  11Comments  ·  Source: handlebars-lang/handlebars.js

Is it possible to assign a variable within a template and use it like variables from outside?

Example:
I want output a table, but 1 column is optional, depend on data (fields[].field2) exists or not.

In each row it is no problem to check, but how to check it for the header ?

<table>
  <thead>
    <tr>
      <th>Head 1</th>
      <th>Head 2 (optional)</th>
      <th>Head 3</th>
    </tr>
  </thead>
{{#each fields}}
  <tr>
    <td>{{{field1}}}</td>
    {{#if field2}}<td>{{{filed2}}}</td>{{/if}}
    <td>{{{field3}}}</td>
  </tr>
{{/each}}
</table>

At the moment i use a unsteady helper function "assign" which creates helpers.

{{#each fields}}
  {{#if field2}}
    {{assign "helperVar" "<th>Head 2 (optional)</th>"}}
  {{/if}}
{{/each}}

Output with: {{{helperVar}}}

But thats not a good solution and i cant use it in #if.

Most helpful comment

:+1:

@kpdecker We can have loops, if statements, and a number of other logic constructs in templates. But apparently assigning a variable is _too_ much logic in templates? I really don't get the reasoning behind that decision when the other default helpers contain way more logic than simply having the ability to assign a variable.

All 11 comments

This goes against the premise of logicless templates and I don't think that this should be language-level construct.

I think the recommended approach here would be to calculate this data in your context creation logic and pass it into the template. This allows for much more control as you have the full javascript language at your disposal rather than whatever subset is implemented in the template language.

template({
  fields: fields,
  hasField2: _.any(fields, function(item) { return item.field2; })
});

I think this would be a good feature, not to introduce more logic to the template, but to pass in variables that is specific to that template.

For example, 2 of my templates use the same partial. I would like to be able to pass some variables to that partial from the template level so that different things is output for the different template within the scope of the partial.

+1

+1

:+1:

:+1:

@kpdecker We can have loops, if statements, and a number of other logic constructs in templates. But apparently assigning a variable is _too_ much logic in templates? I really don't get the reasoning behind that decision when the other default helpers contain way more logic than simply having the ability to assign a variable.

+1

+1

+1

+1

Something along these lines can be implemented using block parameters and is documented here:
http://handlebarsjs.com/block_helpers.html#block-params

Since this is done in a separate namespace outside of the current context, it provides more consistent behavior over context assignment.

Was this page helpful?
0 / 5 - 0 ratings