0

My Aim: Learn the limitations (if any) on parameters that I can send from the controller to view. Right now, I'm checking if I can send any Twirl's keyword (e.g., @, @for, etc.) from the controller function to the view, and then reload a part of the page using JS.

We can pass a raw HTML to the view while using as(HTML) in a controller function. However is it possible to send a block of scala.html type code with all their syntax sugar from the controllers' function to views' related JS function; so that it can show it in the related div? For example how/can I can pass the following:

<p style="padding:1rem;"> @for(i <- items){<h2>i.name</h2} </p>

If I wrap the above in a controller function:

Ok(<p style="padding:1rem;"> @for(i <- items){<h2>i.name</h2} </p>).as(HTML)

Rightfully so, I will get the following error; as the code is not pure HTML:

enter image description here

So Is there a way? or all the template related engine's keywords can not be send from the controller to the view?; and only need to be used on the views' files.

o-0
  • 1,630
  • 12
  • 27
  • Beyond your own aim to learn this, is there any specific use case you want to achieve? I am having a hard time figuring out the advantage of this approach. – Anton Mar 28 '16 at 08:39
  • @Anton it could be used as part of a faster streaming solution, obviously iff the ratio of server(s)/client(s) is not a problem. – o-0 Mar 29 '16 at 04:05

1 Answers1

1

twirl code is compiled on server into regular scala functions (see https://www.playframework.com/documentation/2.5.x/ScalaTemplateUseCases#Tags-%28they-are-just-functions,-right?%29 )

you can eg create a file like renderItems.scala.html

@(items: List[Item])
<p style="padding:1rem;"> @for(i <- items){<h2>@i.name</h2} </p>

and call it like

Ok(renderItems(items))
OlegYch
  • 1,100
  • 7
  • 14
  • also here is an interesting approach you might find useful https://github.com/brikis98/ping-play – OlegYch Mar 28 '16 at 19:00
  • Thanks, going to Play! with it a little bit, and then update all, and if necessary this answer, on this. – o-0 Mar 29 '16 at 04:11