Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Scala/Mustache: Creating a comma separated list

DZone's Guide to

Scala/Mustache: Creating a comma separated list

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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/

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}