Javascript – How to accomplish an if/else in mustache.js

javascriptmustachetemplates

It seems rather odd that I can't figure how to do this in mustache. Is it supported?

This is my sad attempt at trying:

    {{#author}}
      {{#avatar}}
        <img src="{{avatar}}"/>
      {{/avatar}}
      {{#!avatar}}
        <img src="/images/default_avatar.png" height="75" width="75" />
      {{/avatar}}
    {{/author}}

This obviously isn't right, but the documentation doesn't mention anything like this. The word "else" isn't even mentioned 🙁

Also, why is mustache designed this way? Is this sort of thing considered bad? Is it trying to force me to set the default value in the model itself? What about the cases where that isn't possible?

Best Answer

This is how you do if/else in Mustache (perfectly supported):

{{#repo}}
  <b>{{name}}</b>
{{/repo}}
{{^repo}}
  No repos :(
{{/repo}}

Or in your case:

{{#author}}
  {{#avatar}}
    <img src="{{avatar}}"/>
  {{/avatar}}
  {{^avatar}}
    <img src="/images/default_avatar.png" height="75" width="75" />
  {{/avatar}}
{{/author}}

Look for inverted sections in the docs: https://github.com/janl/mustache.js#inverted-sections