Explain Codes LogoExplain Codes Logo

How do I accomplish an if/else in mustache.js?

javascript
prompt-engineering
interview-preparation
logicless-templates
Nikita BarsukovbyNikita Barsukov·Dec 11, 2024
TLDR

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.

{ "loggedIn": true, "user": "Alice" } {{#loggedIn}} Hello, {{user}}! {{/loggedIn}} {{^loggedIn}} Please log in. {{/loggedIn}}

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:

const viewModel = { user: data.user || 'Guest', // If no user, then it's a 'Guest' loggedIn: !!data.user // Coercing to Boolean, it's an all or nothing here, no maybes };

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:

{ "weather": "rainy", "umbrella": true } {{#weather}} {{#umbrella}} Look at you, ready for a downpour! ☔️ {{/umbrella}} {{^umbrella}} I hope you glammed up your rain dance! 💃🌧️ {{/umbrella}} {{/weather}}

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:

const settings = { defaultImageUrl: "path/to/default/image.jpg", // other settings... }; {{#image}} <img src="{{.}}" alt="Gorgeous user-submitted image"> {{/image}} {{^image}} <img src="{{defaultImageUrl}}" alt="Vanilla, but nothing wrong with classics"> {{/image}}

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:

// Using Moxy-Stencil parameterized helpers <% if loggedIn && hasMessages %> Secret messages await you. 🕵️‍♀️ <% else %> All silent on the western front, partner. 🤠 <% endif %>

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!).