Dynamic layout selection in grails 3

65 views Asked by At

With sitemesh possible to use different layout for same pages. For example for mobile and PC users

But how to do this with grails? In documentation and article nothing about this case written I have tried tag in view.gsp, not working

<meta name="layout" content="${defineLayout()}"/>

Any ideas?

2

There are 2 answers

0
demon101 On

By grails code exploration I have found GroovyPageLayoutFinder class it has line

final Object layoutAttribute = request.getAttribute(LAYOUT_ATTRIBUTE);

I can just put org.grails.layout.name attribute to request in Interceptor. It works like a charm!

0
Jeff Scott Brown On

You can use any dynamic expression to express the name of the layout. For example...

<meta name="layout" content="${someVariable}"/>

That expression could reference model variables, or session attributes or request parameters, etc.

See the project at https://github.com/jeffbrown/demon101dynamiclayout.

https://github.com/jeffbrown/demon101dynamiclayout/blob/a383176ccc728a93a05a365638149dde8c548737/grails-app/views/layouts/plain.gsp

<!doctype html>
<html lang="en" class="no-js">
<head>
    <title>
        <g:layoutTitle default="Grails"/>
    </title>
    <g:layoutHead/>
</head>

<body>

<H1>This Is A Plain Ole Layout</H1>
<g:layoutBody/>

</body>
</html>

https://github.com/jeffbrown/demon101dynamiclayout/blob/a383176ccc728a93a05a365638149dde8c548737/grails-app/views/demo/index.gsp

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <meta name="layout" content="${dynamicLayout ?: 'main'}">
    <title></title>
</head>

<body>

</body>
</html>

https://github.com/jeffbrown/demon101dynamiclayout/blob/a383176ccc728a93a05a365638149dde8c548737/grails-app/controllers/demon101dynamiclayout/DemoController.groovy

package demon101dynamiclayout

class DemoController {

    def index() {
    }

    def plain() {
        render view: 'index', model: [dynamicLayout: 'plain']
    }
}