我有一个使用spring和freemarker的国际化应用程序。我正在使用。
从本地化属性文件中获取内容${rc.getMessage("help.headings.frequently_asked_questions")}
对于某些内容,属性值中有回车符。因为我正在网页中显示,我想用这些替换它们。
这样做的最佳方式是什么?
编辑:看得更近似乎我在属性文件中实际上没有回车符。这些属性将作为单行字符串返回。
有没有更好的方法来声明属性,以便他们知道它们是多行的?
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.
干杯, 皮特
答案 0 :(得分:12)
${springMacroRequestContext.getMessage("help.headings.frequently_asked_questions", [], "", false)?html?replace("\n", "<br>")}
答案 1 :(得分:2)
<#escape x as x?html?replace('\n', '<br>')>...</#escape>
工作正常。
如果您希望这是默认行为,请考虑按照此博客中的建议编写自定义TemplateLoader:http://watchitlater.com/blog/2011/10/default-html-escape-using-freemarker/。
答案 2 :(得分:2)
要处理CR + LF(回车+换行)行的结尾,以及仅LF,请执行以下操作:
<#escape x as x?html?replace("\\r?\\n","<br />",'r')>...</#escape>
答案 3 :(得分:1)
至于
有没有更好的方法来声明属性,以便他们知道它们是多行的?
您的问题的一部分,也许这会有所帮助:您可以使用\r
和\n
转义序列在您的媒体资源值中加入行终结符字符,就像API documentation of java.util.Properties#load(java.io.Reader)
中所述
答案 4 :(得分:0)
我建议为它编写自定义指令(请参阅freemarker.template.TemplateDirectiveModel
),因此在模板中可以编写类似<@my.textAsHtml springMacroRequestContext.getMessage(...) />
的内容。重要的是,这是一个指令,而不是函数,因此它在<#escape x as x?html>...</#escape>
内正常工作。否则它会被双重逃脱。使用指令也可以提供最高性能,因为您可以直接将输出发送到输出Writer
,而不是首先构建String
。