Programming Guy
Programming Guy

Reputation: 7461

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 PIN field blank.\
You will be taken through the steps to create a PIN the first time you log in.

Cheers, Pete

Upvotes: 14

Views: 17354

Answers (6)

rortegat
rortegat

Reputation: 81

I found a way to deal with this by splitting the text and adding a
tag between every new line like this:

<#assign splittedText = originalText?split('/n') />
<#list splittedText as textLine>
    ${textLine} <br/>
</#list>

Upvotes: 2

Joman68
Joman68

Reputation: 2850

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>

Upvotes: 3

Felix
Felix

Reputation: 6104

<#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/.

Upvotes: 2

Chaquotay inactive
Chaquotay inactive

Reputation: 2232

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).

Upvotes: 1

ddekany
ddekany

Reputation: 31162

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.

Upvotes: 0

${springMacroRequestContext.getMessage("help.headings.frequently_asked_questions", [], "", false)?html?replace("\n", "<br>")}

Upvotes: 18

Related Questions