8.3.11 Named URL Mappings

URL Mappings also support named mappings, that is mappings which have a name associated with them. The name may be used to refer to a specific mapping when links are generated.

The syntax for defining a named mapping is as follows:

  1. static mappings = {
  2. name <mapping name>: <url pattern> {
  3. // ...
  4. }
  5. }

For example:

  1. static mappings = {
  2. name personList: "/showPeople" {
  3. controller = 'person'
  4. action = 'list'
  5. }
  6. name accountDetails: "/details/$acctNumber" {
  7. controller = 'product'
  8. action = 'accountDetails'
  9. }
  10. }

The mapping may be referenced in a link tag in a GSP.

  1. <g:link mapping="personList">List People</g:link>

That would result in:

  1. <a href="/showPeople">List People</a>

Parameters may be specified using the params attribute.

  1. <g:link mapping="accountDetails" params="[acctNumber:'8675309']">
  2. Show Account
  3. </g:link>

That would result in:

  1. <a href="/details/8675309">Show Account</a>

Alternatively you may reference a named mapping using the link namespace.

  1. <link:personList>List People</link:personList>

That would result in:

  1. <a href="/showPeople">List People</a>

The link namespace approach allows parameters to be specified as attributes.

  1. <link:accountDetails acctNumber="8675309">Show Account</link:accountDetails>

That would result in:

  1. <a href="/details/8675309">Show Account</a>

To specify attributes that should be applied to the generated href, specify a Map value to the attrs attribute. These attributes will be applied directly to the href, not passed through to be used as request parameters.

  1. <link:accountDetails attrs="[class: 'fancy']" acctNumber="8675309">
  2. Show Account
  3. </link:accountDetails>

That would result in:

  1. <a href="/details/8675309" class="fancy">Show Account</a>