Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala/Play: load template dynamically

I have this Scala/Play application and I have to fetch a bunch of templates via AJAX. I'm doing something like this now:

def home = Action {
    Ok(views.html.home())
}

def about = Action {
    Ok(views.html.about())
}

def contact = Action {
    Ok(views.html.contact())
}

//etc

But this is just creating an action for every template. Can I do something like this instead:

def loadTemplate(templateName) = Action {
    //Load template from "views" with name being value of parameter templateName
}

Is this possible on Play Framework? If so then how?

Play Framework 2.2.1 / Scala 2.10.3 / Java 8 64bit

UPDATE: My original question might have been misunderstood. I don't want to compile a template, I want to fetch already compiled one in a more dynamic way.

UPDATE2: I think I found something very close, if not exactly what I need on this answer, but it's in Java and I need it in Scala.

like image 419
Caballero Avatar asked Feb 14 '23 12:02

Caballero


1 Answers

Using scala reflection:

object Application extends Controller {

  import reflect.runtime.universe._
  val currentMirror = runtimeMirror(Play.current.classloader)
  val packageName = "views.html."

  def index(name: String) = Action {
    val templateName = packageName + name

    val moduleMirror = currentMirror.reflectModule(currentMirror.staticModule(templateName))
    val methodSymbol = moduleMirror.symbol.typeSignature.declaration(newTermName("apply")).asMethod

    val instanceMirror = currentMirror.reflect(moduleMirror.instance)    
    val methodMirror = instanceMirror.reflectMethod(methodSymbol)

    Ok(methodMirror.apply().asInstanceOf[Html])
 }

 }
like image 150
Nilanjan Avatar answered Feb 17 '23 02:02

Nilanjan