Use template variables in a GlimmerJS component

Bram Borggreve
InstructorBram Borggreve

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

In this lesson we will add a variable called content to our component class, initialize it as a string and display the variable in our class using the double curly braces syntax, which is the handlebars expression for expressions, { {content }}.

After this we create a new class variable called items, initialize it as an array with strings. To display this list in our template we add a <ul></ul> and inside this unordered list we use the handlebars each helper to display the list items.

And inside our each statement we will print a <li> tag and render {{ item}} inside it.

  {{#each items key="@index" as |item| }}

[00:00] Our current components have static text in the templates. In order to use the text from the component class, we open up component.ts and we add a property called content, and set the value to a string.

[00:14] In the template of hps, we replace the content of the DIV with towards content surrounded by the double curly braces, the handlebar syntax for an expression. When the page refreshes, we see the new content. A very common use case when building web applications is that we want to loop over an array of items. In our class, we create a property called items, which we initialize as an array and inside that array, we create a couple of strings.

[00:42] We open our template and create an unordered list. Inside our Ul, we invoked a handlebar each helper. The first parameter is to name our class property items. The second parameter is key, which we set to array index using at index. This is needed by the glimmer-vm, so it can track value updates.

[01:03] The last parameter is as and then item between pipelines. This is how we can refer to each of our items. We close the each helper using forward slash each. Inside our each typeprint, will print an li tag with our item. When we save the file, we see that the list of items gets printed.