Loading...

February 20, 2011

Grails Goodness: The Link Namespace

Grails supports named URL mappings. We can define a name for a URL mapping and use that name when we generate links in our application. In this post we see how we can use the link namespace to use a named mapping.

We start with a simple named URL mapping for viewing product details on our site:

// File: grails-app/conf/UrlMappings.groovy
...
name productDetails: "/product/details/$ref" {
    controller: 'product'
    action: 'details'
}
...

We can use the <g:link mapping="..." .../> tag in our code to use this named URL mapping:

<%-- Sample GSP --%>

<g:link mapping="productDetails" params="[ref: product.identifier]" class="nav">Details</g:link> 
outputs for product with identifier '901':
<a href="/context/product/details/901" class="nav">Details</a>

But we can also use the special link namespace in our code. We start a new tag with link as namespace. The name of the tag is the name of the URL mapping we have created. The attributes we specify are all converted to parameters for the link. If we add the attrs attribute we can specify attribute key/value pairs that need to be applied to the generated link as is.

<%-- Sample GSP --%>

<link:productDetails ref="${product.identifier}" attrs="[class: 'nav']">Details</link:productDetails> 
outputs for product with identifier '901':
<a href="/context/product/details/901" class="nav">Details</a>