Working on refreshing the “tasty views and layouts” chapter for Grails in Action 2.0 and came across the gem that is the g:external tag.

Grails 2.0 introduced this cute little tag called <g:external> for that very common case of linking to CSS, JavaScript and favicons. Back in the old days, you used to use some kind of “resource” link, perhaps as a method call for brevity (or in the even older days you might have used a createLinkTo tag, but that’s showing my age):

<link rel="stylesheet" href="${resource(dir:'css',file:'hubbub.css')}" />

But these days, <g:external> is the tag for you! It will sense whether you’re linking to css, javascript, some kind of image (for a favicon), or that crazy Apple-icon-specific-thing, and generate the appropriate <link> tag for you. Behold the magic of external:

<g:external dir='css' file='hubbub.css'/>

This will generate the full <link> text you need, including the appropriate context for your app:

<link href="/hubbub/static/css/hubbub.css" type="text/css" rel="stylesheet" 
       media="screen, projector" dir="css" file="hubbub.css" 
       contextPath="/hubbub"/>

But the truly wonderful part of the little gem of a tag (as you’ll notice in the generated code above) is that it is resources-aware. That means that you get cache-able goodness of the resources plugin, along with all the static-mapping magic that exposes to you.

There is also a uri version of the tag has a little less ceremony where you link context relevant content and it will be scooped up and re-written, however it didn’t seem to happen for me on 2.2.0…

<g:external uri='/css/hubbub.css'/>

No time to waste! Go forth and externalise! Just perfect for your next CSS, JS and Favicon <link> usage!

(Oh, PS. if you’re after a Grails 2.0 book to get started, shameless plugin for Grails in Action 2.0 which is in MEAP.)

&nbsp;