tags:

views:

996

answers:

2

I've been going through the book "The Definitive Guide to Rails" (Rocher/Brown) and in Chapter 04, this mysterious thing called a "layout" just appeared with no explanation. (And there's no "layout" in the index. As far as I know, it's never explained.)

How does the system know to "inherit" the pages from layout/main.gsp? There's nothing about "layouts" in the index, and it seems to have just appeared.

On their sample app, a simple store site, the URL mappings for the / homepage say

  "/"(controller:"store")

and store controller's empty "index" closure

package com.g2one.gtunes

class StoreController {

    def index = {
    }
}

simply tells it to render store/index.gsp

The store/index.gsp just has a few lines of HTML; no layout gets included with any directive

<html>
    <head>
     <meta http-equiv="Content-type" content="text/html; charset=utf-8">
     <meta name="layout" content="main">
     <title>gTunes Store</title>
     <g:javascript library="prototype"></g:javascript>
    </head>
    <body id="body">
     <h1>Your online music store and storage service!</h1>
     <p>Manage your own library, browse music and purchase new tracks as they become available</p>
    </body> 
</html>

When I run the sample the page shown for "/" isn't just this simple HTML, it's the contents of "layouts/main.gsp" with this information magically inserted inside it.

I don't see how the information in layout/main.gsp gets applied to the page, how the elements get mixed together. I've been following through the book page by page and this functionality just "appeared' with no explanation.

+2  A: 

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.

John Stoneham
+4  A: 

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).

Lloyd Meinholz
Thanks! It was staring me right in the face. I didn't think to look in a "meta" tag when all the other grails directives looked like <g: !
ראובן