[英]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. 在带有Play Framework 2的Scala中,我想存储一个模板,稍后再渲染。 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)) 示例:var indexTemplate:模板= Template(“ views.html.Index”)OK(indexTemplate(用户,上下文))
You can make indexTemplate
an abstract def
that would be implemented by any Controller
that extends it: 您可以将indexTemplate
为abstract def
,任何扩展它的Controller
都可以实现它:
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. 这类似于Secure Social使用的ViewTemplates
模式,不同之处在于它们使用整个特征来注入已实现的模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.