Skip to content

Where's my `if` syntax?

Andrew Theken edited this page Apr 28, 2016 · 3 revisions

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?

Testing for Existence

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:

An Example Template:
Dear {{#name}}{{.}}{{/name}}{{^name}}{{../job_title}}{{/name}}

This template will either:

  1. Render name if it is "truthy" or,
  2. 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:

Here's an example where name is present:

Model:

{
  "name" : "Alice",
  "job_title" : "CEO"
}

Result:

Dear Alice
Here's an example where name is absent:

Model:

{
  "job_title" : "CEO"
}

Result:

Dear CEO
name may also be false or null and will produce the same result as when absent:

Model:

{
  "name" : null,
  "job_title" : "CEO"
}

Result:

Dear CEO

Final thoughts:

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.