In a template, you can use if
to conditionally render content.
There are 2 styles of if
: block and inline.
<div class=>
This div used the inline "if" to calculate the class to use.
</div>
Content for the block form of "if"
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
:
<div class="badge ">
Badge Text
</div>
Block if
Motivation
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
.
Usage
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.
Inline if
Motivation
Sometimes, you will want to conditionally set an argument or attribute.
For instance, consider two components that display a user's avatar. One is for a recipient and the other for a sender.
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.
Usage
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.
Learn More
Please see the API documentation of the if
helper for more patterns.