質問

i'm trying to figure out how to most elegantly integrate something like PHP's nl2br() function into a current project done with JSF2/Spring. I could easily create getters using something like return text.replaceAll("\n","<br/>"); in my model classes, however that does seem like putting view related code where it does not belong. I have the same feeling about storing actual html content in my database. I guess the cleanest solution would be using tags/EL for this, however i couldn't find something that seemed to do just that. How would you guys implement something like this? Thank you in advance, any hints are highly appreciated!

役に立ちましたか?

解決

Use either CSS, assuming that the text doesn't contain any HTML

<div style="white-space: pre">#{bean.text}</div>

Or create a custom EL function and then display it unescaped (Facelets implicitly escapes HTML)

<div><h:outputText value="#{my:nl2br(bean.text)}" escape="false" /></div>

You should only make absolutely sure that it's free of XSS.

他のヒント

Well, in the first place JSF is a Web UI framework. So, anything that you expect to output to the user will end as HTML (with the only exception of javascript, though). So, I don't find it a grave violation of MVC (if any at all). Maybe you could even push the envelope and directly use <br/> inside the text, instead of replacing \n

In a more general sense, if you have different lines/paragraphs in your text, the more flexible/standard solution would be break your text in the different elements and let your presentation logic handle it. So, instead of a properties with

 presentationPage.introductionText=Ipse Lorum ...sum.\nVini vidi vinci.

You would end with

 presentationPage.introductionText.par1=Ipse Lorum ...sum.
 presentationPage.introductionText.par2=vini vidi vinci.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top