I have a String variable which contains carriage returns and new lines \r\n.
text = "Text1\r\nText2\r\nText3";
I’m presenting it using <h:outputtext>.
<h:outputText value="#{bean.text}" />
But it doesn’t recognize the new line characters and shows as below in webbrowser.
Text1 Text2 Text3
Why doesn’t the <h:outputText> break \n into new lines?
What should I do? Do I have to replace \n with <br />?
Linebreaks in HTML are represented by
<br />element, not by the\ncharacter. Even more, open the average HTML source code by rightclick, View Source in browser and you’ll “see”\nover all place. They are however not presented as such in the final HTML presentation. Only the<br />will.So, yes, you need to replace them by
<br />. You can use JSTL functions for this:Note: when using Apache EL instead of Oracle EL, double-escape the backslash as in
\\n.Otherwise you will face an exception with the message
Failed to parse the expression with root cause org.apache.el.parser.ParseException: Encountered <ILLEGAL_CHARACTER>.This all is however ugly and the
escape="false"makes it sensitive to XSS attacks if the value comes from enduser input and you don’t sanitize it beforehand. A better alternative is to keep using\nand set CSSwhite-spaceproperty to preformatted on the parent element. If you’d like to wrap lines inside the context of a block element, then setpre-wrap. Or if you’d like to collapse spaces and tabs as well, then setpre-line.E.g.