Grails Cookbook - A collection of tutorials and examples

Grails createLink Tag Example

The Grails createLink Tag renders the necessary path or url to a resource depending on the given parameters. This does not render an anchor tag, but just the URL that can be used inside an anchor tag, JavaScript, etc. Here are some examples


createLink Tag

If an application has the context myapp (E.g. you deployed the app as myapp.war), the path to access it is /myapp (E.g. http://localhost:8080/myapp). If we have this code inside our GSP:
<g:createLink controller="person" action="create" />

This will render:

/myapp/person/create

This means
  • myapp - is the context of the application we wish to access
  • person - is the controller to invoke
  • create - is the action to invoke in the controller

This is useful because sometimes we need the URL information outside anchor tags. For example:

<script>
   function createPerson() {
      window.location.href = '<g:createLink controller="person" action="create" />';
   }
</script>

Will render:

<script>
   function createPerson() {
      window.location.href = '/myapp/person/create';
   }
</script>

createLink with id parameter

Here is an example on how to use the tag passing an id parameter.
<g:createLink controller="person" action="show" id="1"/>

This will render:

/myapp/person/show/1

This is useful for creating links when the primary key is known.

createLink with arbitrary parameters

Here is an example of using the tag with multiple parameters using any names.

<g:createLink controller="person" action="search" 
   params="[firstName: 'John', lastName: 'Doe', age: '10']"/>

This will render

/myapp/person/search?firstName=John&lastName=Doe&age=10


Other Grails Tag Examples


Tags: createLink, Grails Tag