Mark is a graph advocate and field engineer for Neo Technology, the company behind the Neo4j graph database. As a field engineer, Mark helps customers embrace graph data and Neo4j building sophisticated solutions to challenging data problems. When he's not with customers Mark is a developer on Neo4j and writes his experiences of being a graphista on a popular blog at http://markhneedham.com/blog. He tweets at @markhneedham. Mark is a DZone MVB and is not an employee of DZone and has posted 516 posts at DZone. You can read more from them at their website. View Full User Profile

Scala/Mustache: Creating a comma separated list

06.23.2011
| 4835 views |
  • submit to reddit

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!

From http://www.markhneedham.com/blog/2011/06/22/scalamustache-creating-a-comma-separated-list/

Published at DZone with permission of Mark Needham, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Sirikant Noori replied on Sun, 2012/01/15 - 12:36pm

mkString would work well if we just wanted to join strings together but we actually wanted to wrap each of the elements into a link tag as well and that type of logic really does go in the view!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.