Views and layouts
Controllers & Views
Grails supports the creation of views using either JavaServer Pages (JSP) or Groovy Server Pages (GSP). This section describes how to provide a model to views. For a more complete reference on see the GSP and JSP references.
Syntactically GSP and JSP are very similar the main difference being that code within scriptlets is in Groovy not Java! Grails controllers uses a convention mechanism to delegate to an appropriate view. For example an action called list will delegate to a "list" view:
class BookController {
def list = {
["books" : Book.list() ]
}
}
The corresponding view for the above action would need to be placed in the "grails-app/views/book" directory with the name "list.jsp" or "list.gsp". The example below is in GSP:
<html> <head> <title>Book list</title> </head> <body> <h1>Book list</h1> <table> <tr> <th>Title</th> <th>Author</th> </tr> <g:each in="${books}"> <tr> <td>${it.title}</td> <td>${it.author}</td> </tr> </g:each> </table> </body> </html>
Defining Layouts
Layouts can be created through Grails's support for SiteMesh. There are 2 ways to create layouts the first is to associate a view with a layout at the "layout" meta tag to your page:
<html>
<head>
<meta name="layout" content="main"></meta>
</head>
<body>This is my content!</body>
</html>
Now create a layout called "main.gsp" in the "grails-app/views/layouts" directory and you're done!:
<html>
<head>
<title><g:layoutTitle default="An example decorator" /></title>
<g:layoutHead />
</head>
<body onload="${pageProperty(name:'body.onload')}">
<div class="menu"><!--my common menu goes here--></div>
<div class="body">
<g:layoutBody />
</div>
</body>
</html>
The layout uses GSP tags to apply the layout onto the target page.
Layout by Convention
The second way to associate layouts is to use "layout by convention". For example, if you have a controller such as:
class BookController {
def list = { ... }
}
You can create a layout called grails-app/views/layouts/book.gsp which will be applied to all views that the BookController delegates to.
Alternatively, you can create a layout called grails-app/views/layouts/book/list.gsp which will only be applied to the list action within the BookController.
If you have both the above mentioned layouts in place the layout specific to the action will take precedence when the list action is executed.