1

I'm curious as to whether Mustache has a syntax feature that is the opposite of the "Inverted Selection" syntax {{^foo}}.

Let's say we have the data:

{
  people: [
    { name: "Alice" },
    { name: "Bob" },
    { name: "Mallory" }
  ]
}

And the template:

<h3>People</h3>
<ul>
  {{#people}}
    <li>{{name}</li>
  {{/people}}
</ul>

If we wanted to add an item if there are no people, we just add something like:

{{^people}}<li>No people</li>{{/people}}

But in my case I don't want to show the <h3> and <ul> if there are no people.

A syntax like {{?people}} (representing the opposite / boolean negation of {{^people}}) would be perfect for this situation, but does one exist?


Another alternative would be to preprocess the data, adding a value

has_people = Boolean(people.length)

and using {{#has_people}}, but this seems counter-intuitive and against the logic-less (and I use that term lightly) paradigm.

azz
  • 5,852
  • 3
  • 30
  • 58

1 Answers1

0

Simplest solution seemed to be to add the functionality myself.

I've forked the Mustache.js repository with the changes required to introduce the {{? data }} selector. In English it could be read as 'When true, or there are items within data.'

Repository | Diff 1 | Diff 2

azz
  • 5,852
  • 3
  • 30
  • 58
  • Why not just use Handlebars if you're going through with all this? The functionality is all already there. – Etheryte Jun 04 '14 at 17:48
  • 1
    You're probably right. I've used handlebars a little in the past, but for this project I've been using plain Mustache. I've found that it has lead to very clean templates. – azz Jun 04 '14 at 17:58