February 22, 2011

Grails Goodness: Encode Content with the encodeAs Tag

Encoding and decoding values is easy in Grails. We can invoke the dynamic methods encodeAs...() and decodeAs...() for several codecs. If we have a large block of content on our Groovy Server Page (GSP) we want to encode we can use the <g:encodeAs codec="..."/> tag. The body of the tag is encoded with the codec we specify with the codec attribute.

<%-- Sample.gsp --%>

<h1>Sample Title</h1>

<g:encodeAs codec="HTML">
<h1>Sample Title</h1>

If we look at the generated HTML source we see:

<h1>Sample Title</h1>

&lt;h1&gt;Sample Title&lt;/h1&gt;