-
Notifications
You must be signed in to change notification settings - Fork 18
Where's my `if` syntax?
You might have noticed, Mustachio doesn't have any if-else
syntax built in. This was done deliberately in Mustache, for some good reasons, and we tried to keep Mustachio as close to Mustache as we could.
Does this mean you can't show or hide content conditionally?
Of course not! Mustache and Mustachio allow you a great amount of flexibility, but the flow control is more "declarative" than "imperative." So what does this mean?
The key difference between the way we'd choose to conditionally execute application code, and the way we choose what to render is based on whether a value is present in a model, or absent ("truthy" or "falsey"). So, let's take a simple case and show how you can both render content when a value is present, and when it is absent:
Dear {{#name}}{{.}}{{/name}}{{^name}}{{../job_title}}{{/name}}
This template will either:
- Render
name
if it is "truthy" or, - Render
job_title
if it is not present:
(Make special note of the {{ . }}
syntax to reference name
and {{ ../job_title }}
to "move up" a level in the scope.)
Now, let's have a look at what the output is for a few different models:
Model:
{
"name" : "Alice",
"job_title" : "CEO"
}
Result:
Dear Alice
Model:
{
"job_title" : "CEO"
}
Result:
Dear CEO
Model:
{
"name" : null,
"job_title" : "CEO"
}
Result:
Dear CEO
It may seem a bit odd to author templates without explicitly including conditionals, but hopefully it's clear that one can achieve the same results with "logic-less templates," while requiring remembering less syntax.