Luke
Luke

Reputation: 5708

Passing template instance data as a keyword argument to a nested template

I have a template, called skillbar, which takes two keyword arguments, title and value.

So, for example, I could type:

  {{>skillbar title="strength"  value=51}}

To render a skillbar with the label "strength" that has its progress bar filled up 51%.


I have a bunch of these skillbars I would like to create and rather than doing something like:

{{>skillbar title="strength"     value=51}}
{{>skillbar title="willpower"    value=80}}
{{>skillbar title="imagination"  value=30}}

Id rather create a separate template, which I can register a helper on that contains an array of objects that I can use as parameters.

Template.abilities.helpers({
  abilities: [
    {title: 'strength',    value: 51},
    {title: 'willpower',   value: 80},
    {title: 'imagination', value: 30} 
  ]
}); 

Presumably then, I could {{#each}} over the abilities array in my markup can create the skillbar template instances that way.

This encapsulates the essence of what I want to do, but it throws a syntax error:

<template name="abilities">
  {{#each abilities}}
    {{>skillbar title={{title}} value={{value}} }}
  {{/each}}
</template>

Upvotes: 1

Views: 34

Answers (1)

saimeunt
saimeunt

Reputation: 22696

Use this syntax instead :

<template name="abilities">
  {{#each abilities}}
    {{> skillbar}}
  {{/each}}
</template>

When invoking a child template, if you don't pass any argument its current data context will be set to the parent one, which happens to be the currently iterated over ability from the {{#each}} loop.

Alternatively you could use this syntax :

<template name="abilities">
  {{#each abilities}}
    {{> skillbar title=title value=value}}
  {{/each}}
</template>

But in this specific case it would be redundant, but could be useful to rename parameters for whatever reason.

Upvotes: 1

Related Questions