Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using curly braces in JavaScript in Play Framework template

I have passed a list of titles that I have passed through from my controller:

@titles:List[String]

I want to cycle through generating some html headings with {mmm} appearing after:

@titles.map { title =>
  <h1>{title} {mmm}</h1>
}

Clearly there is a problem as it will try and find a variable called mmm. How do I escape the brackets?

Or is there a more idiomatic way to generate the HTML that doesn't involve mapping the list? Very new to this!

like image 961
Matthew Pickering Avatar asked Jul 19 '12 16:07

Matthew Pickering


2 Answers

You shouldn't need to escape curly brackets in Play—unlike in Scala's XML literals, they don't have any special meaning in Play templates except after an @.

You should be able to write the following:

@titles.map { title =>
  <h1>@{title} {mmm}</h1>
}

And get <h1>Whatever Title {mmm}</hq>, etc.

like image 78
Travis Brown Avatar answered Sep 30 '22 00:09

Travis Brown


Travis' answer demonstrates one possibility (for that you asked for) and it's correct. On the other hand you can also meet other cases and you need to keep in mind other tricks:

for an example this will fail:

@for(title <- titles){
    Title: @title {mmm} <br/>
}

But this will work (thanks Travis)

@for(title <- titles) { 
    Title: @{title} {mmm} <br/> 
}

And this will work as well

@for(title <- titles){
    Title: @title - <b>something else without bracets</b> <br/>
}

Alternative

Alternatively you can create for an example toBrackets() method in your model and call it in your template (Java sample)

public String toBrackets(String string) {
    return "{" + string + "}";
}

in template:

@for(title <- titles){
    Title: @title @title.toBrackets("mmm") <br/>
}
like image 25
biesior Avatar answered Sep 29 '22 23:09

biesior