Loading...

Friday, February 27, 2009

Show HTML as HTML in Grails

Starting with Grails on a little project I already learned something. In a domain object, Wish, I had a String property, description, which can contain HTML code. For example we can use the following value for the description property: This description is<br />two lines..

Following the Grails reference documentaiton I created a GSP file and used ${fieldValue(bean: wish, property: 'description'} to output the value. When I look a the output I got:

This description is <br />two lines.

The HTML was already encoded and the < and > brackets where replaced by &lt; and &gt; automatically.

I changed the GSP file and used ${wish.description} and I got what I wanted:

This description is
two lines.

We can use encodeAsHTML() and decodeHTML() methods to get the same effect. So for example if we use ${wish.property.encodeAsHTML() the < and > brackets are automatically replaced again.

6 comments:

phaggood said...

When I try to display a string containing HTML I don't get the results you describe above. I.e. into my rich editor widget I type "doctors and medical providers used[enter][enter]Doctor 1[enter]Doctor 2[enter]" which I save in the field entryText. In my GSP I try:

${showItem.entryText}

Which displays "doctor and medical providers used

", then I try
${showItem.entryText.encodeAsHTML()}
which displays:
doctor and medical providers used<br><br>
Then I try
${showItem.entryText.decodeHTML()}
which repeats the first display.

mrhaki said...

@phaggood Can you see in the database the contents of the entryText field? And which version of Grails are you using. I used 1.0.4 for my example.

Codezilla said...

Using Grails 1.1

Yes, in my table is stored "doctor and medical providers used

..."; GrailsUI's rich editor takes my control characters and turns them into HTML.

Codezilla said...

that should be 'doctors and medical prividers used br br'; Blogger seems to have stripped them today.

mrhaki said...

You can also check your Config.groovy and look for the property grails.views.default.codec. You can set it to html, so all is encoded as html.

naamanc said...

Thanks for your post..
Your more recent post - http://mrhaki.blogspot.com/2011/02/grails-goodness-encode-content-with.html - is also helpful with this topic..

Naaman

Post a Comment