首页 > 解决方案 > 如何在 Play Framework 的 Twirl 中将隐式值从一个模板布局传递到另一个模板布局?

问题描述

假设我有这个控制器的动作:

def getPost = Action { implicit request => Ok(views.html.post("bla bla bla")) }

现在我有两种布局:

// baseLayout.scala.html:
@(title: String)(content: Html)(implicit req: RequestHeader)
<html>
  ...
  @content
  ...
</html>

// postLayout.scala.html:
@(title: String)(content: Html)(implicit req: RequestHeader)
@baseLayout(title) { // Error: Cannot find any HTTP Request Header here
  <h1>Post</h1>
  @content
}

然后我有这个模板:

// post.scala.html
@(post: String)(implicit req: RequestHeader)
@postLayout("First post") {
  <div>@post</div>
}

此代码无法编译。我收到这个错误

Cannot find any HTTP Request Header here (See up)

这就像隐式RequestHeader成功传输:从模板Actionpost模板,然后从post模板到postLayout模板。

但它不会从postLayout模板传输到baseLayout模板。

我怀疑这是因为在postLayout模板中,隐式出现在Html块之后,它可能会丢弃任何隐式传播。除此之外,我没有看到任何解释,我完全迷失了。

标签: scalaplayframeworktwirl

解决方案


推荐阅读