Outputting the contents of a String variable in Freemarker

Today I ran across one of those things that should be simple, but is not. I call a remote service to get product information and I display that information in the store through a Freemarker Template. Normally this is not an issue. I normally just ${x} where x is my variable and it is all good. However I ran across and instance where the product title had some HTML code in it. Yes, I know that the title should not have HTML code in it, but that is beside the point. When Freemarker finds HTML characters like & in a String variable, it decides to clean it up by escaping the HTML code. For example it would replace & with & This cause my page to display badly because all of those escaped HTML characters made one long string with no whitespace that just messed the columns of one part of the page.

I could not find anything in the Freemarker documentation that describes how to just output the String variable in raw form. I saw that if it was a String litteral like " " I could do the following ${r" "} but there is nothing similar for a variable. Fortunately I did find ofbiz’s work around for this problem. What they did is implement a StringWrapper that does nothing but hides the String in a wrapper class whose toString method calls the toString method of the wrapped String. Now Freemarker does not know it is a String and outputs the raw value from the toString method.

Things like this really frustrate me. By default if I say print out a variable I expect the language to just print out the raw value. If I want it formatted for HTML I should have to do something special, not the other way around.

This entry was posted in Simple things made difficult. Bookmark the permalink.

One Response to Outputting the contents of a String variable in Freemarker

  1. Do you have a Facebook fan page for your site?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>