Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load twirl template dynamically

In my Scala project I use Twirl template engine. Template files structure is duplicated for russian and english languages so for example I have the following two paths: en.Send.txt.MonoEnsure and ru.Send.txt.MonoEnsure

In my code I want to be able to dynamically load en or ru template, something like this:

def render(lang: String) = lang.Send.txt.MonoEnsure("hi")
render("en") // does not work, just to illustrate my point

How can I achieve this?

like image 673
src091 Avatar asked Jun 17 '26 22:06

src091


1 Answers

I think this is the code that should achieve that:

import play.twirl.api.Template1

def getTemplate[T](name : String)(implicit man: Manifest[T]) : T =
  Class.forName(name + "$").getField("MODULE$").get(man.erasure).asInstanceOf[T]

def render(lang: String) = 
  getTemplate[Template1[String,String]](s"$lang.Send.txt.MonoEnsure").render("hi")

render("en")

Templates are compiled to BaseScalaTemplate so you can call it using reflection. You only need to know the number of params of your template so that you can load it as instance of trait play.api.twirl.TemplateX. In this case Template1[String, String] (first String for the parameter and second one for the type of the render response).

Check this thread for more info about reflection in scala How do I call a Scala Object method using reflection?

like image 125
moliware Avatar answered Jun 20 '26 23:06

moliware



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!