Search code examples
grailsgrails-controller

Grails g:include can it be done?


Im wondering if it is possible to use g:include to include only the body contents of a given page.

Say i have a main layout page as follows:

<html>
  <head>
    <title>My start page</title>
    <g:layoutHead>
  </head>
  <body>
    <g:layoutBody>
  </body>
</html>

Then a main page (index.gsp)

<html>
  <head>
    <!-- main layout reference -->
    <meta name="layout" content="main"/>
  </head>
  <body>
    THIS IS MY INDEX BODY CONTENT WITH AN INCLUDE
    <g:include controller="book" action="list"/>
    <g:link controller="book" action="list">See the full list!</g:link>
  </body>
</html>

And finally the book/list page

<html>
  <head>
    <!-- main layout reference -->
    <meta name="layout" content="main"/>
  </head>
  <body>
    <table>
    <g:each in="${books}">
      <tr>
        <td>${it.author}</td>
        <td>${it.title}</td>
        <td>${it.price}</td>
      </tr>
    </g:each>
    </table>
  </body>
</html>

So what i want to achieve is that the main page (index.gsp) only includes the table defined in the book/list page. However, when i try this it includes the entire html defined (<html> tags and all).

is it possible to do this somehow? i've tried things like <g:include controller="book" action="list" view="someView.gsp"/> however this doesn't work. I really want to avoid having to add a book list logic to the "index controller" i want to reuse my existing controller.

I can't be the first person out there having this usecase, what solutions have you guys come up with?


Solution

  • You can use the applyLayout tag. Simply create an empty.gsp layout with only:

    <g:layoutBody/>
    

    And then decorate your include tag with applyLayout:

    <g:applyLayout name="empty">
      <g:include controller="book" action="list"/>
    </g:applyLayout>
    

    See the entry on the Grails guide for further reference.