Conditional Sections
Often, you want to show or hide part of your view depending on whether a particular condition is met. For example you might want to show a slightly different view to users depending on whether they're signed in or not.
Step 1
In this example we've already set up a mock sign-in mechanism – click the 'sign in' button and enter your name in the prompt.
All we need to do is hide the 'please sign in' message when we're signed in, and the 'welcome back!' message when we're not.
Wrap the first block in an #if
section that uses the signedIn
property:
{{#if signedIn}}
<!-- message for signed-in users -->
<p>Welcome back, {{username}}!</p>
{{/if}}
Now do the same for the other block, except with the notSignedIn
property. Execute the code.
The plain mustache block
{{#...}}
is equivalent to{{#if ...}}{{#with ...}}
. It is both conditional and contextual.
Step 2
Having two properties (signedIn
and notSignedIn
) to represent one piece of data (whether or not the user is signed in) is the sort of thing that makes most programmers itch uncontrollably.
We have a couple of options. We could use an #unless
section:
{{#unless signedIn}}
<!-- not-signed-in block -->
{{/unless}}
There's also a plain mustache for negated sections,
{{^signedIn}}...{{/}}
.
Alternatively, we could use else:
{{#if signedIn}}
<!-- signed-in block -->
{{else}}
<!-- not-signed-in block -->
{{/if}}
Update the template. Then, remove the references to notSignedIn in the JavaScript. Then breathe a sigh of relief – doesn't that feel better?
If you have another branch in your conditional, you can include it with an
{{elseif ...}}
mustache. An{{#if}}
section can include as manyelseif
s as you need, but it can only contain oneelse
.