Pergunta

I have a template that has to include another template based on the file name that comes from the database. For example, here is a template that takes a String that contains the name of the template file that will be included in another template.

@(sourceCodeFileName: Option[String])
@{sourceCodeFileName match {
    case Some(sourceCode) => {
        @sourcecode.sourceCodeFileName + "scala.html"
    }
}}

Where sourcecode is the package where the actual template resides. For example., if the String parameter to the above template is given as myview, then I want to include myview.scala.html. Is there a way to do this in Play framework?

Foi útil?

Solução

To inject HTML from a static file to a scala template, you can define a function in your template:

@import scala.io.Source

@injectHtmlFromFile(sourceCodeFilename: String) = { @{
    Html(Source.fromFile("static/html/" + sourceCodeFilename + ".html").mkString)
}}

…and call it later in the template this way:

@injectHtmlFromFile(sourceCode.sourceCodeFileName)
Side note

I'm not sure I quite understand the question – I've answered the OP's comment and the same question posted by him on Google Groups.

Outras dicas

A Play scala template is a function returning Html. You should obtain the template object in the controller and pass it to the template. But in simple cases it's just easier to pass the rendered Html:

Your template would then look like this:

@(content: Option[Html])
@content

and the controller:

object Application extends Controller {
  def index = Action {
    val sourceCodeFileName= ...
    Ok(Some(Class.forName("views.html."+sourceCodeFileName)
        .getConstructor().newInstance().asInstanceOf[() => play.api.templates.Html]()
      ))
  }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top