If-Else Logic in Mustache.js (Sort Of)

For those of you who may not be familiar with it, Mustache.js is a logic-less templating engine for JavaScript. What do I mean by “logic-less”. Well, simply put, it means that Mustache.js lacks structures common to many programming languages; there’s no way to do things like for-loops or function calls (as we may be familiar with them) from within a template. The goal behind this lack of structure is to force you to keep your display logic and your view (templates) completely separate.

Luckily, if you code your templates properly you can emulate if-else like behavior in your templates using inverted-sections. According to the Mustache documentation, an inverted-section is a section that:

[M]ay render text once based on the inverse value of the key. That is, they will be rendered if the key doesn’t exist, is false, or is an empty list.

What this means is that we can use sections to print a value if it’s filled in, else we use an inverted-section to print a value if that value is not filled in:

<script id="channelTpl" type="text/html">

    <img src = "http://placehold.it/80x80">

    <span>[No Name Provided]</span>


Here we’re saying that if the `` of our channel is empty, you’ll see “[No Name Provided]” in the rendered template.