Grails Cookbook - A collection of tutorials and examples

Grails createLinkTo Tag Example

The Grails createLinkTo Tag renders the path or url to a static resource. For example: css, images, and javascript files. This does not render an anchor tag or image tag to the resource, but just the URL that can be used inside others tags, JavaScript, etc. Here are some examples


createLinkTo 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:createLinkTo dir="images" file="icon.png" />

This will render:

/myapp/images/icon.png

This means that <YOUR-GRAILS-PROJECT>/web-app/images/icon.png is the one accessed and must exist. Here is the breakdown of the components:
  • myapp - is the context of the application we wish to access
  • images - the directory inside web-app
  • icon.png - the resource to link to

We can use it like this

<img src="${createLinkTo(dir:'images', file:'icon.png'}">

This will render:

<img src="/myapp/images/icon.png">

Here is another example:

<script>
   function viewImage() {
      window.location.href = '<g:createLinkTo dir="images" file="icon.png" />';
   }
</script>

This will render:

<script>
   function viewImage() {
      window.location.href = '/myapp/images/icon.png';
   }
</script>

Tags: createLinkTo, Grails Tag