Changing layout template in runtime

房东的猫 提交于 2019-11-30 14:54:24
Jonathan Dixon

I see 2 options to accomplish what you're after. The first would be to pass a theme parameter to your templates (i.e. something to tell the called template which theme/layout to use) and use that parameter to conditionally call a layout template. The second would be to handle the condition inside the controller by returning the appropriate view based on the selected theme.

Option 1

In your action you will want to pass some value to your template to indicate which theme to use.

def index = Action {
  Ok(views.html.index("two-col"))
}

Then in your index.scala.html you would do something like this:

@(theme: String)

@content = {
  <h1>Action Specific Content</h1>
}

@if("two-col" eq theme) {
  @twoCol("title")(content)
} else {
  @main("title")(content)
}

This would expect there to be a twoCol.scala.html template, such as:

@(title: String)(content: Html)
<!DOCTYPE html>
<html>
  ...
  <body>
    <h1>Two Column</h1>
    @content
  </body>
</html>

Note: You can also pass the theme using an implicit parameter, see this SO question. This would alleviate the need to explicitly pass it the template on every render.

Option 2

This would be as simple as the following in your controller, but would possibly require much more repeated code in the view templates.

def index = Action {
  var theme = ...
  ...
  if (theme eq 'tow-col') {
    Ok(views.html.twocol.index("two-col"))
  } else {
    Ok(views.html.default.index())
}

This assumes there is a twocol and default package in /app/views that have an index.scala.html.

Additional Comments

As you can tell from option 1, index.scala.html is not tightly coupled with main.scala.html. You can replace the call to main with a call to any other template, or even no template.

FWIW, I would go with option 1 and It would possibly evolve into a better solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!