简体   繁体   中英

How do I store a pointer to a template in scala Play Framework 2?

In Scala with Play Framework 2 I would like to store a template that I will render later. Here is a code example:

trait TraitController {
    self:Controller =>
    var indexTemplate = null // This is the variable I would like to 
                             // store the template pointer.
    def index()  = Action { 
        var user :User
        var context :Context
            ... 

            OK(indexTemplate(user, context))
        }

object MyController extends Controller with TraitController {
    indexTemplate = views.html.Index
}

The routes file has an entry in it that looks like

GET     /index              controllers.MyController.index()

Any idea how this can be accomplished?

Bonus Marks: How could I find a template given a string. Example: var indexTemplate: Template = Template("views.html.Index") OK(indexTemplate(user, context))

You can make indexTemplate an abstract def that would be implemented by any Controller that extends it:

trait TraitController {
    self: Controller =>

    def indexTemplate(user: User, context: Context): Html

    def index()  = Action { 
        ... 
        Ok(indexTemplate(user, context))
    }
}

object MyController extends Controller with TraitController {
    def indexTemplate(user: User, context: Context): Html = views.html.Index(user, context)
}

This is similar to the ViewTemplates pattern used by Secure Social , except they use an entire trait to inject the implemented templates.

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