Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

h:outputText does not break \r\n characters into new lines

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 />?

like image 570
Pellizon Avatar asked Feb 01 '13 13:02

Pellizon


People also ask

How do you break a line in Primefaces?

Add attribute escape="false" in h:outputText . If your value contains <br /> then you will have break line in text.

What is \n line break?

Newline (frequently called line ending, end of line (EOL), next line (NEL) or line break) is a control character or sequence of control characters in a character encoding specification (e.g., ASCII, EBCDIC) that is used to signify the end of a line of text and the start of a new one.

How do I stop a line breaking in HTML?

The <nobr> HTML element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text.

What does \n do in HTML?

The \n character matches newline characters.


1 Answers

Linebreaks in HTML are represented by <br /> element, not by the \n character. Even more, open the average HTML source code by rightclick, View Source in browser and you'll "see" \n over 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:

<... xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions">  <h:outputText value="#{fn:replace(bean.text,'\n','&lt;br/&gt;')}" escape="false" /> 

Note: when using Apache EL instead of Oracle EL, double-escape the backslash as in \\n.

<h:outputText value="#{fn:replace(bean.text,'\\n','&lt;br/&gt;')}" escape="false" /> 

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 \n and set CSS white-space property to preformatted on the parent element. If you'd like to wrap lines inside the context of a block element, then set pre-wrap. Or if you'd like to collapse spaces and tabs as well, then set pre-line.

E.g.

<h:outputText value="#{bean.text}" styleClass="preformatted" /> 
.preformatted {     white-space: pre-wrap; } 
like image 200
BalusC Avatar answered Sep 23 '22 06:09

BalusC