Yeti Yeti - 2 years ago 115
Scala Question

Scala/Java template list iteration and concatenation of string

I want to iterate over a list of strings, concatenate them with the suffix/prefix "" and if it's not the last entry of the list append a comma at end.

Wanted Output example: "circle","cube","banana"

My first try is the following snippet:

@listStringifier(list: List[String]) = @{
if (list != null && !list.isEmpty) {
for ((string, index) <- list.zipWithIndex){if(index != list.size-1){"string",}

But this function is always empty when I use @listStringifier anywhere.

Logging within the @listStringifier block shows that it is iterating, but not assigning anything.

If I call the for loop directly in the template like this following snippet it works:

@if (list != null && !list.isEmpty) {
for ((string, index) <- list.zipWithIndex){if(index != list.size-1){"@string",}

But I dont want to iterate several times so I want to assign the concatenated string to a variable afterwards.

Any help would be appreciated,
thanks in advance

Answer Source

I think mkString can do what you want

list.mkString( "'" , "','" , "'" )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download