Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Routing and Templates

Templates and Handlebars Syntax

Learn Ember template syntax - mustaches, escaping, if and each blocks, let, attributes and class bindings, comments and the template tag format - with runnable stand-ins.

An Ember template describes what the user sees. It looks like HTML with a few extras written between double curly braces, called mustaches. The syntax is based on Handlebars, but Ember's version is a stricter, faster language that compiles to efficient update instructions, so only the parts that change are touched in the DOM.

Real versus stand-in. The template snippets are real Ember syntax, shown read-only. The runnable blocks build a tiny template engine in plain JavaScript so that you can experiment with the idea of mustaches, if and each. It is not Ember's compiler; for example, real templates are compiled once and updated in place instead of being re-rendered as strings.

Two ways to write templates

Modern Ember keeps the template inside the JavaScript file, in a <template> tag. These are .gjs (JavaScript) or .gts (TypeScript) files:

JavaScript
// app/templates/about.gjs
<template>
  <h2>About us</h2>
</template>

Older projects use a separate .hbs file next to the JavaScript. The language inside is identical. The difference is that with the template tag you import what you use (helpers, modifiers, other components), so the file explains its own dependencies. This track uses .gjs.

Printing values

JavaScript
<template>
  <h1>{{@title}}</h1>          {{! an argument }}
  <p>{{this.message}}</p>      {{! a property of the component }}
  <p>{{@user.name}}</p>        {{! a path into an object }}
</template>
  • {{@x}} is an argument, {{this.x}} is the component's own property, and a path like @user.name follows properties down.
  • Output is escaped: if @title is <b>hi</b> the page shows the characters, not bold text. This protects against cross-site scripting. To output trusted HTML you must mark it explicitly (the htmlSafe function from @ember/template), and you should do that only for content you control or have sanitized.
  • Missing values print nothing. null, undefined and false render as empty.

Comments

JavaScript
<template>
  {{! This comment does not appear in the page }}
  {{!-- Use this form if the comment contains }} --}}
  <!-- An HTML comment would be sent to the browser -->
</template>

Conditionals: if, else, unless

JavaScript
<template>
  {{#if @user}}
    <p>Welcome back, {{@user.name}}.</p>
  {{else if @isGuest}}
    <p>Welcome, guest.</p>
  {{else}}
    <p>Please sign in.</p>
  {{/if}}

  {{#unless @items}}
    <p>Nothing here yet.</p>
  {{/unless}}
</template>

There is also an inline form that works as an expression, handy in attributes:

JavaScript
<template>
  <button class={{if @active "btn btn-active" "btn"}}>Save</button>
  <p>{{if @count @count "none"}}</p>
</template>

What counts as false?

In {{#if}}, the values false, null, undefined, 0, NaN, the empty string and empty arrays are all falsy. Empty arrays being falsy is a handy Ember feature: {{#if @posts}} means "there is at least one post". Use {{#if (eq @count 0)}} when you need exact comparisons (eq comes from a helper such as ember-truth-helpers).

JS A mini template engine: mustaches and if

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Loops: each

JavaScript
<template>
  <ul>
    {{#each @posts as |post index|}}
      <li>{{index}}: {{post.title}}</li>
    {{else}}
      <li>No posts yet.</li>
    {{/each}}
  </ul>
</template>
  • as |post index| names the block parameters: the current item and its zero-based index.
  • The {{else}} branch runs when the list is empty, so you do not need a separate if.
  • For long lists that change, give Ember a stable identity with key: {{#each @posts key="id" as |post|}}. This lets Ember reuse DOM elements instead of re-creating them. The default key (@identity) is usually right.
  • To loop over an object's keys, use {{#each-in @settings as |key value|}}.

Local values with let

let names the result of an expression for use inside a block. It avoids repeating long paths:

JavaScript
<template>
  {{#let @order.customer.address as |address|}}
    <p>{{address.street}}, {{address.city}}</p>
  {{/let}}
</template>
JS Mini engine: each with index and else

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Attributes and classes

Mustaches work inside attribute values. Use the @ and this paths as usual:

JavaScript
<template>
  <a href={{@url}} title="Open {{@name}}">{{@name}}</a>
  <input value={{this.query}} disabled={{@isLocked}} />
  <div class="card {{if @featured "card-featured"}} {{@extraClass}}"></div>
</template>
  • A boolean attribute such as disabled is present when the value is truthy and removed when falsy.
  • Without quotes, value={{this.query}} sets the property to the exact value; with quotes the value is converted to a string.
  • Learn about forwarding unknown attributes to an element with ...attributes in Component Patterns.

Calling helpers

Parentheses call a helper as a value (sub-expression); without them it is a statement:

JavaScript
import { concat, get } from '@ember/helper';

<template>
  <p>{{concat "Hello, " @first " " @last}}</p>
  <p>{{get @scores "math"}}</p>
  <p class={{if (gt @count 10) "big"}}>{{@count}}</p>
</template>

Strings are written with double or single quotes; numbers and true/false/null are literals. gt here comes from an add-on; the built-in helpers are covered in Helpers and Modifiers.

What templates cannot do

Templates are deliberately limited: no arbitrary JavaScript, no assignments, no loops with counters. Logic belongs in the class (a getter) or in a helper. If a template becomes hard to read, move the logic into a getter such as get visiblePosts() and print that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when @title contains the text <b>hi</b> and the template has {{@title}}?

    Mustaches escape HTML. Trusted HTML needs explicit marking with htmlSafe, which you should use sparingly.
  2. 2. What does {{else}} do inside {{#each}}?

    The else branch of each renders only when there are no items.
  3. 3. How are the item and index named in an each block?

    Block parameters are written between pipes after as.
  4. 4. Which of these is treated as falsy by {{#if}} in Ember templates?

    Empty arrays are falsy in templates, which makes {{#if @posts}} a convenient "has items" check.
  5. 5. Where should complicated logic go, rather than in a template?

    Templates stay simple; derive values in a getter and print the result.

Summary

  • Mustaches print escaped values: {{@arg}}, {{this.prop}}, {{@user.name}}.
  • Use {{#if}}/{{else}}/{{#unless}} and the inline (if a b c) for conditions; empty arrays are falsy.
  • {{#each list as |item index|}} loops and has an {{else}} for empty lists; {{#let}} names a local value.
  • Mustaches work in attribute values; boolean attributes appear or disappear.
  • Put logic in classes and helpers; keep templates readable.

Next: Links, Navigation and the Router Service