handlebars.js

Is it possible to assign a parameter value within handlebars templates without using helpers?


I am trying to assign values within a template, the idea is to do something like this:

    {{#if author}}
        {{className = 'classA'}}  <- trying to implement this line.
    {{else}}
        {{className = 'classB'}}
    {{/if}}

<div class={{className}}></div>

Is it possible to do so without registerHelper?


Solution

  • You can do this with a partial.

    partial:

    <div class="{{classname}}">{{var1.author}}</div>
    

    template:

    {{#if author}}
    {{> mypartial var1=. classname="classA"}}
    {{else}}
    {{> mypartial var1=. classname="classB"}}
    {{/if}}
    

    In this example I've passed the current scope as var1. I can't recall if the scope stays the same and the new variable is just added to it or if you have to pass the scope manually.