Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a string array with handlebars

Lets say I have an array like this in ember controller,

selectedUsers: ["Popeye", "Sulley", "Gru"];

Now, how can i render each users in an unordered list using handlebars? Can i use the {{#Each}} helper?

like image 784
Irshu Avatar asked Dec 25 '13 13:12

Irshu


People also ask

How do I iterate through an array in Handlebars?

To iterate over an object with JavaScript and Handlebars. js, we can use the #each keyword. to add the Handlebars script and the template for looping through each entry in data . We use #each this to loop through each array property.

Are Handlebars helper?

Helpers can be used to implement functionality that is not part of the Handlebars language itself. A helper can be registered at runtime via Handlebars. registerHelper , for example in order to uppercase all characters of a string.

What is the syntax for each loop in Handlebars?

{{#foreach}} is a special loop helper designed for working with lists of posts. It can also iterate over lists of tags or users if needed. The foreach helper will output the content placed between its opening and closing tags {{#foreach}}{{/foreach}} once for each item in the collection passed to it.

How do you use unless Handlebars?

You can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value. If looking up license under the current context returns a falsy value, Handlebars will render the warning. Otherwise, it will render nothing.


2 Answers

Yes, you should use an each loop:

<ul>
{{#each selectedUsers}}
    <li>{{ this }}</li>
{{/each}}
</ul>

From the docs:

You can iterate over a list using the built-in each helper. Inside the block, you can use this to reference the element being iterated over.

<ul class="people_list">
  {{#each people}}
    <li>{{this}}</li>
  {{/each}}
</ul>

when used with this context:

{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley"
  ]
}

will result in:

<ul class="people_list">
  <li>Yehuda Katz</li>
  <li>Alan Johnson</li>
  <li>Charles Jolley</li>
</ul>

You can use the this expression in any context to reference the current context.

like image 193
Stoic Avatar answered Oct 24 '22 06:10

Stoic


This also works

<ul>
{{#each this}}
<li>{{ this }}</li>
{{/each}}
</ul>
like image 4
Usman Avatar answered Oct 24 '22 05:10

Usman