{page.title}

Grails Multi-Region Templates

Grails allows you to easily create a view template for all the pages in your application through sitemesh. Making simple HTML tweaks to the default template works if you only have one main content region to your template. Oftentimes though you might want more than this (a content region and a sidebar region for example). Here’s how you can accomplish this.

First modify your main template to look something like this: main.gsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title><g:layoutTitle default="Craig Burke" /></title>
</head>
<body>
<div id="frame">

	<h1>Craig Burke</h1>

	<div id="main-content">
	    <g:pageProperty name="page.main-content" />
	    <g:layoutBody />
	</div>

	<div id="side">
	   <g:pageProperty name="page.side" />
	</div>

</div>

</body>
</html>

You’ll notice that in addition to using the pageProperty tag to denote the main content region (page.main-content), I’ve also included the layoutBody tag directly beneath this. This layoutBody tag will make sure that views that are automatically generated by scaffolded controllers will render those pages correctly as well.

Now, for any view where you’d like to use this template your code will look something like this: index.gsp

  <g:applyLayout name="main">
   
  <content tag="main-content">
     <h2>Main Content</h2>
     <p>Main content goes here</h2> 
  </content>

  <content tag="side">
     <h2>Side Header</h2>
     <p>Side content goes here</p>
  </content>

Pretty slick.