Search code examples
model-view-controllerjsf-2nl2br

nl2br in JSF2 without violating MVC paradigm?


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!


Solution

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