This page last changed on Feb 28, 2006 by glaforge.

Views and layouts

Controllers & Views

Grails supports the creation of views using either JavaServer Pages (JSP) or Groovy Server Pages (GSP). Syntactically they 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 {
      @Property 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. 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 in called "main.jsp" in the "grails-app/views/layouts" directory and you're done!:

Layouts currently must be created in JSP as GSP does not support JSP custom tag libraries and hence is not compatible with SiteMesh. This may change in the future.

<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<html>
       <head>
          <title><decorator:title default="An example decorator" /></title>
               <decorator:head />
      </head>
 <body onload="<decorator:getProperty property='body.onload'/>">
                 <div class="menu"><!--my common menu goes here--></menu>
                 <div class="body">
                      <decorator:body />
             </div>
 </body>
</html>
Document generated by Confluence on Mar 29, 2006 08:46