h:outputText seems to trim whitespace, how do I preserve whitespace?

Solution 1:

The <h:outputText> doesn't trim the value at all.

Perhaps you're talking about whitespace like leading/trailing spaces, tabs, newlines, carriage returns, etc in the value, which have by default totally no meaning in HTML markup. It just becomes part of the HTML source code, but not the HTML presentation. Newlines, for example, are in HTML to be represented by the <br> element, not by the \n character.

If you'd like to preserve the whitespace in a HTML element node as it is in the HTML source code, then you need to set the parent HTML element's CSS white-space property to pre in order to preserve it. If you'd like to wrap lines in block elements, then use pre-wrap.

E.g.

<h:outputText ... styleClass="preformatted" />

with

.preformatted {
    white-space: pre-wrap;
}

An alternative is to convert the text to valid HTML markup yourself. E.g. replacing every occurrence of \n character by the <br/> string. You could use an EL function for this.

See also:

  • Component to inject and interpret String with HTML code into JSF page