How do I replace carriage returns with <br /> using freemarker and spring?
I've got an internationalised app that uses spring and freemarker. I'm getting content from localised property files using.
${rc.getMessage("help.headings.frequently_asked_questions")}
For some of the content there are carriage returns in the property values. Because I'm displaying in a web page I'd like to replace these with
.What is the best way to do this?
Edit: looking closer it seems that I don't actually have carriage returns in the property files. The properties are coming back as single line strings.
Is there a better way to declare the properties so they know they are multi-line?
help.faq.answer.new_users=If you have not yet set a PIN, please enter your username and passcode (from your token) in the boxes provided and leave the PI开发者_JS百科N field blank.\
You will be taken through the steps to create a PIN the first time you log in.
Cheers, Pete
${springMacroRequestContext.getMessage("help.headings.frequently_asked_questions", [], "", false)?html?replace("\n", "<br>")}
To handle CR + LF (carriage return + line feed) line endings, as well as just LF do this:
<#escape x as x?html?replace("\\r?\\n","<br />",'r')>...</#escape>
<#escape x as x?html?replace('\n', '<br>')>...</#escape>
works just fine.
If you want this to be the default behaviour, consider writing a custom TemplateLoader as suggested in this blog: http://watchitlater.com/blog/2011/10/default-html-escape-using-freemarker/.
As to the
Is there a better way to declare the properties so they know they are multi-line?
part of your question, maybe this helps: you can include line terminator characters in your property values by using the \r
and \n
escape sequences, like it is explained in the API documentation of java.util.Properties#load(java.io.Reader)
.
I would recommend writing a custom directive for it (see freemarker.template.TemplateDirectiveModel
), so in your templates you can write something like <@my.textAsHtml springMacroRequestContext.getMessage(...) />
. It's important that this is a directive, not function, so it works properly inside <#escape x as x?html>...</#escape>
. Otherwise it would be double-escaped. Using a directive can also give the highest performance, as you can directly send the output to the output Writer
, rather than building a String
first.
精彩评论