简体   繁体   中英

Dynamic templates in Play Framework 2.0

There is TemplateLoader in Play 1.0 for generating templates in runtime.

Is there any solution to dynamically load template in Play 2.0 ? Or can I somehow convert it to scala code for using Eval ?

For example: I want to store some templates in the database, so that certain users could edit them.

Play 2.0 already compiles your templates to object methods, so you don't have to 'dynamically load' them!

Consider this simple template called app/views/test.scala.html .

@(num:Long) 
Your number is @num

It becomes a Scala method of views.html called test . Evaluate it with this code:

val msg : String = views.html.test(23).toString()

You don't have to use html views only. To use templates with strings, use the play.api.templates.Txt derived classes. This is a template called app/views/quick.scala.txt :

@(id:Long)Your id is @id

It becomes a method views.txt.quick and is used:

val msg2 : String = views.txt.quick(32).body

You can find out more in the documentation for the the play.api.templates package.

It seems the relevant code is in framework/src/play/src/main/scala/system/ApplicationProvider.scala in the Play-2.0 directory, particularly the ReloadableApplication class. I'm unsure how this compiling on the fly would suit you, since you don't want to do it when the template is requested (it is slow). Which means that storing in a database doesn't quite make sense: you don't want to store the template source code, but rather the compiled template object.

For arguments sake, if you just wrote the templates to the app/views directory, you could leave Play to compile them at its leisure. But then, beware, because they probably won't compile on a production system.

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