handlebars: Passing variable to partial inside each

Gregor Voinov picture Gregor Voinov · Jul 27, 2016 · Viewed 8.5k times · Source

I create a list with the block helper #each, but I can't pass variables to my partial inside my each loop.

{{#each a-z.letters}}
    {{this}} /*[1]*/
    <li class="list-inline__item">
        {{>button btn="btn-text" addClass='-large' link='letter/{{this}}' label='{{this}}'/*[2]*/}}
    </li>
{{/each}}

The link partial:

<a href="{{link}}" class="btn-text {{addClass}}">{{label}}</a>

The output is:

<ul class="list-inline">
    A /*[1]*/
    <li class="list-inline__item">
        <a href="letter/{{this}}/*[2]*/" class="btn-text -large">{{this}}/*[2]*/</a>
    </li>
    ....

[1] Just for testing and it works

[2] If i want to pass it inside a partial it doesn't render my params

UPDATE

So this is my helper now to extend my href with an url.

Handlebars.registerHelper('updateLink', function(options){
    var insertAt = "href=";
    var content = options.fn(this).trim();
    var pos = content.indexOf(insertAt) + insertAt.length+1;  // +1 for the quotation marks
    content  = content.slice(0, pos) + options.hash.url + content.slice(pos, content.length);
    return new Handlebars.SafeString(content ); 
});

The link partial:

{{#updateLink url="letters/"}}
    {{>button link=this label=this btn="btn-text" addClass='-large'}} 
{{/updateLink}}

Answer

76484 picture 76484 · Jul 28, 2016

You cannot use the {{}} braces syntax to evaluate data members when you are already inside a set of braces. You can, however, simply reference the member, without wrapping it in quotes, and it will be evaluated:

{{>button btn="btn-text" addClass='-large' link=this label=this}}

You will note that my example above does not include the "letter/" prefix to the link value. Handlebars does not have a way to concatenate strings. To achieve this, you could choose one of the following options:

  • Use a helper (your own or someone else's).
  • Pass the prefix as an additional parameter to your partial.
  • Hard-code the prefix in the partial template.
  • Include the concatenated string in your template data (a-z.letters).