How do I accomplish an if/else in mustache.js?
In Mustache.js, use {{#key}}...{{/key}} for truthy cases and {{^key}}...{{/key}} for falsy cases. No explicit if/else, but this structure checks conditions effectively.
Here, "Hello, Alice!" renders when loggedIn
equals true
, and "Please log in." displays upon loggedIn
equating to false
or undefined.
Setting defaults in the model
In Mustache, templates are best kept logicless. Handle data-related logic within the model or controller instead, and prepare data accordingly. This principle applies when using defaults:
Now, Mustache uses the Boolean value of loggedIn
to decide which section to render.
A simple answer to complex states
Mustache templates are logicless, but that doesn’t mean they can’t handle complex logic. With proper structuring of nested sections and apt use of default states, we can manage complex states:
Nested sections here create a semblance of a nested if/else structure. Neat, huh?
Leveraging global settings
Create a global settings object that holds default values. This practice comes in handy when certain properties might miss from your data model:
The .
refers to the context and renders the image
property if available. Otherwise, it settles with the defaultImageUrl
from the settings object.
Where Mustache stops, alternatives begin
When Mustache.js’s simplicity is not enough, consider Moxy-Stencil, which offers parameterized helpers for advanced conditional logic:
These helpers in views introduce meaningful logic into your templates when you need to spice them up.
Maintenance made easy with Mustache
Logicless templates foster easy code maintenance, reducing future headaches. Here's a few mustache-inspired tips to keep templates crisp:
- Augment properties with logic-based attributes in your data model, not your template.
- Repetitive logic? Use helpers or partials instead to stay DRY.
- Always validate and sanitize data model to avoid mid-run surprises (yikes!).
Was this article helpful?