Changing layout template in runtime

后端 未结 1 1513
清酒与你
清酒与你 2021-01-02 23:01

In Kohana (PHP framework) the layout is implemented through Template_Controller which continas a member variable called $template, which serves as layout view. Then in the a

相关标签:
1条回答
  • 2021-01-02 23:48

    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.

    0 讨论(0)
提交回复
热议问题