How to handle string or array of strings in mustache template

lmsurprenant picture lmsurprenant · Feb 4, 2014 · Viewed 10k times · Source

I have a simple/beginner question for using mustache templating in my app (or Hogan more accurately). I am using an API which sometimes returns a String and sometimes returns an Array of Strings.

I know could wrap the String in a single-element array, but is there also a way to handle this optionality from the mustache template?

Using normal sections like
{{#stringOrArray}} <li>{{.}}</li> {{/stringOrArray}} doesn't print the value if its just a String.

Answer

Jezcentral picture Jezcentral · Jun 13, 2014

I know it is a bit late, but here is what I use:

{{#test.length}}
    {{#test}}<li>{{.}}</li>{{/test}}
{{/test.length}}

{{^test.length}}
    <li>{{test}}</li>
{{/test.length}}

It's like feature detection. The first block of code checks to see if test has a length, if it does, it is an array (yes, I know strings are supposed to have a length property, too, but they don't). It will either output the array (if it is an array), or nothing (if it isn't). The second block prints out the value of test if it has no length (i.e. it is a string or integer etc) This means you can use it on:

var data = {
    test: "test1"
}

OR

var data = {
    test: [ "test1", "test2", "test3" ]
}

without having to set a flag for whether it is an array or not. Mustache will output both, but the one you don't need will be blank.