Scala/Mustache: Creating a comma separated list
We’re using the Mustache templating engine on my project at the moment and one thing that we wanted to do was build a comma separated list.
Mustache is designed so that you pretty much can’t do any logic in the template which made it really difficult to do what we wanted.
It’s easy enough to get a comma after each item in a list with something like the following code:
{{#people}}<a href="/link/to/{{toString}}">{{toString}}</a>{{/people}}
where people is passed to the template as a collection of strings.
To get rid of the trailing comma we ended up building a collection of Pairs containing the person’s name and a boolean value indicating whether or not to show the comma.
We need to show the comma before every element except for the first one so we can pass the following collection to the template:
val values = names.zipWithIndex.map { case(item, index) => if(index == 0) (item, false) else (item, true) }
zipWithIndex returns a collection of pairs containing the original strings and their position in the collection.
We can then map to a different result for just the first element and then use those pairs in the template like so:
{{#people}} {{#_2}}, {{/_2}}<a href="/link/to/{{_1}}">{{_1}}</a>{{/people}}
It’s truly horrendous so if anyone knows a better way then please let me know!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.