Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Grails know to apply a "layout" to pages it renders?

Tags:

layout

grails

The <meta name="layout" content="main"> tag includes the layout in the gsp page.

You can view the grails-app/views/layouts/main.gsp to view and modify the layout. You can copy main.gsp to mymain.gsp, modify it, then change layout entry in the gsp page to reference mymain.gsp instead of main.gsp and experiment with customizing your layout preserving your ability to easily back out your changes.

Grails uses sitemesh under the covers (like it uses hibernate and spring) to do view layouts. There is a web-app/WEB-INF/sitemesh.xml configuration file in the project directory as well. This particular file isn't that helpful, but it references a class in the groovy project if you wanted to deeply understand how grails is using sitemesh (this probably isn't necessary).


Here's your directive:

<meta name="layout" content="main">

main.gsp contains <g:layoutHead> and <g:layoutBody>, where the <head> and <body> content of the index.gsp are folded into the layout to create the final page.


One recent trick that appears to work, if you name your layout to match your controller it appears (in Grails 2.3.4 at least) to automatically use that template.

For example, my controller:

// grails-app/controllers/myapp/HomeController.groovy
package myapp
class HomeController {
    def index() {
        [ myvar: "Test" ]
    }
}

my layout:

// grails-app/views/layouts/home.gsp
<html>
  <head></head>
  <body>
    <h1>Home</h1>
    <g:layoutBody />
  </body>
</html>

my view:

// grails-app/views/home/index.gsp
<p>${ myvar }</p>

renders using the home layout.

Also, you can specify a layout for all your actions in a controller like this:

class HomeController {
    static layout = "someotherlayout"

    // actions will render using grails-app/views/layouts/someotherlayout.gsp
}