简体   繁体   中英

Play! + Scala: Split string by commnas then Foreach loop

I have a long string similar to this:

"tag1, tag2, tag3, tag4"

Now in my play template I would like to create a foreach loop like this:

@posts.foreach { post =>
    @for(tag <- @post.tags.split(",")) {
        <span>@tag</span>
    }
}

With this, I'm getting this error: ')' expected but '}' found.

I switched ) for a } & it just throws back more errors.

How would I do this in Play! using Scala?

Thx in advance


With the help of @Xyzk, here's the answer: stackoverflow.com/questions/13860227/split-string-assignment

Posting this because the answer marked correct isn't necessarily true, as pointed out in my comment. There are only two things wrong with the original code. One, the foreach returns Unit , so it has no output. The code should actually run, but nothing would get printed to the page. Two, you don't need the magic @ symbol within @for(...) .

This will work:

@for(post <- posts)
    @for(tag <- post.tags.split(",")) {
        <span>@tag</span>
    }
}

There is in fact nothing wrong with using other functions in play templates.

This should be the problem

@for(tag <- post.tags.split(",")) {
    <span>@tag</span>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM