Groovy & Grails: Views with GSP

Site Admin · 11 Sep 2026 · 8 views

GSP Is HTML with Groovy

GSP, Groovy Server Pages, is the Grails view technology. Files live under grails-app/views and mirror the controller and action names. A GSP file is mostly HTML with small tags and expressions that inject dynamic data. The expression syntax in dollar sign braces prints a value.

<h2>Welcome to the library</h2>
<p>There are ${Book.count()} books.</p>

The expression runs on the server and inserts the result into the page before it is sent to the browser.

Conditionals and Loops

The g namespace provides view tags. g:if tests conditions, and g:each repeats content for every element in a collection.

<g:if test="${books}">
    <ul>
        <g:each in="${books}" var="book">
            <li>${book.title} by ${book.author}</li>
        </g:each>
    </ul>
</g:if>
<g:else>
    <p>No books found.</p>
</g:else>

The each tag loops through the books list and exposes each element as book, and the li body renders one row per book. When the list is empty, the else tag shows a friendly message.

Links and Forms

Tag libraries also build URLs and forms safely. The link tag creates anchors with the application context applied automatically.

<g:link controller="book" action="show" id="7">Details</g:link>

The form tags generate the hidden state and error handling too. A create view binds form fields back to a command or domain instance, which keeps the round trip of user input and validation errors together.

Reusable Layouts

Grails uses a layout for the shared page shell: header, navigation, sidebar, and footer. Each view declares which layout to use, and the content is merged into the layout body.

<meta name="layout" content="main">

Most Grails apps need only one main layout, and changing the brand or navigation updates every page at once.

Key Points

  • GSP files mix plain HTML with server-side Groovy expressions.
  • g:if and g:each render conditionals and repeating rows.
  • Form and link tags generate correct URLs and keep validation state.
  • Layouts provide one shared page shell for the whole application.
Share this post:

Comments (0)

Please login or register to comment.