Search code examples
arraysjsonconditional-statementsmustache

Mustache templating, how can I return an array of strings?


I'm currently trying to do mustache templating on the following json:

 {
  "jsonMessage": {
    "errorFileLocations": [
      "File1",
      "File2"
    ]
  }
}

I can use [{{jsonMessage.errorFileLocations}}] to get the following in http://mustache.github.io/#demo

[File1,File2]

However I want to display ["File1", "File2] to replicate how it is in the JSON.

I've tried a selector like so:

[{{#jsonMessage.errorFileLocations}}"{{.}}",{{/jsonMessage.errorFileLocations}}]

And I get ["File1","File2",], which is slightly closer but I need to deal with the trailing comma somehow. Is this something mustache handles that I'm missing?

Thank you!


Solution

  • Mustache does not have a standard, notational way to tackle this, at least not yet. Power lambdas would make it possible to create a notation for this in a portable way. Some implementations already have a similar feature in their own, non-standard way, or some other way to tackle trailing separators.

    However, like with most things that Mustache has no notation for, you can work around it by adjusting the input data. Change it to this:

    {
      "jsonMessage": {
        "errorFileLocations": [
          {"value": "File1", "first": true},
          "File2"
        ]
      }
    }
    

    note that you only need to change the first array element; subsequent elements can remain plain strings. Now write your template like this:

    [{{#jsonMessage.errorFileLocations}}{{#first}}"{{value}}"{{/first}}{{^first}}, "{{.}}"{{/first}}{{/jsonMessage.errorFileLocations}}]
    

    I happen to be the creator of Wontache, a new Mustache implementation for JavaScript with a stronger focus on specification compliance. It has a playground, which has more features and is much more up-to-date with the mustache specification than the demo on mustache.github.io. It also has an updated version of the mustache(5) manpage. You can copy-paste the code below into the load/store box of the playground in order to try out the solution I described above:

    {"data":{"text":"{\n  \"jsonMessage\": {\n    \"errorFileLocations\": [\n      {\"value\": \"File1\", \"first\": true},\n      \"File2\"\n    ]\n  }\n}"},"templates":[{"name":"no-trailing-comma","text":"[{{#jsonMessage.errorFileLocations}}{{#first}}\"{{value}}\"{{/first}}{{^first}}, \"{{.}}\"{{/first}}{{/jsonMessage.errorFileLocations}}]"}]}
    

    Like Mustache.js and many other implementations, Wontache does not yet offer a notational solution for trailing separators. I hope to implement power lambdas by the end of May, though.