In a template, you can use if
to conditionally render content.
There are 2 styles of if
: block and inline.
Additionally, you can use template helpers like concat
within a conditional. For the example below, if @color
has a truthy value, such as 'navy'
, the div classes will include badge-navy
:
Let's take a look at two components that display a person's username.
The components look similar, don't they? The first component shows extra information about the user's local time.
Let's say we tried to create a single username
component.
If the <Username>
tag doesn't specify a @localTime
argument,
we will see an extra, incomplete text, their local time is
, on the screen.
What we need is a way to display the local time if @localTime
exists.
We can do this with an if
.
This is the syntax for an if
statement in block form.
If the condition
is true, Ember will render the content that is inside the block.
Like many programming languages, Ember also allows you to write if else
and
if else if
statements in a template.
The block form of the if
statement is typically used to wrap
HTML elements or another block. If you want to use if
inside of an HTML element, keep reading to learn about how to use inline if
instead.
Here's an example of a block if
, wrapping some HTML elements:
Again, the two components look similar.
The first component has an is-active
class, while the second a current-user
class.
How should we unify the components into one?
The is-active
class is responsible for showing the active icon.
How that icon is rendered may change over time,
so we won't use ...attributes
to apply the is-active
class.
Instead, we'll pass the argument @isActive
to dictate what to do (e.g. render the icon).
As for the current-user
class, it may have been just one of a few classes
that can be applied to the <aside>
element.
Let's use ...attributes
to apply the current-user
class.
We take these API designs into account and end up with a reusable component.
The component uses an inline if
to conditionally apply the is-active
class.
Afterwards, we can refactor the initial components.
When passing a literal JavaScript value to a component,
we have to wrap the value in double curlies (e.g. @isActive={{true}}
).
A value that isn't wrapped in curlies is assigned as string,
which matches the behavior in HTML attributes.
For example, writing @isActive=true
will set @isActive
to the string 'true'
.

This is the syntax for an if
statement in inline form.
If the condition
is true, Ember will use value
at the invocation site.
Ember also allows you to write an if else
statement in inline form.
It looks similar to a ternary operator.
Similarly to block if
, you need to pay attention where inline if
is placed.
Inline if
can be used only inside attribute values
of HTML elements. For example: