[SalesForce] Visualforce – Preserve Whitespace in apex:outputText

I've records with fields values containing more than one white space. The White spaces are preserved in the back-end but while displaying it on the Visualforce page, the white spaces are reduced to only one white space. I'm looking for something like <pre>. I tried with CSS property white-space:pre/pre-wrapbut it didnt work. Using pre tag with apex tags are bringing in the alignment issues even with css property display:inline-block.
The lines displayed below for outputText with spaced replaced as '&nbsp;' in the class are displayed text as it is in the page, like A&nbsp;&nbsp;B

<apex:outputText escape="false"> {!myText}</apex:outputText>

OR

<apex:outputText escape="false" value="{!myText}"/>

Sample details:
Original data: A B

Expected: A B

Actual: A B

Space after A in the above text has been trimmed to single whitespace.
I tried with but no change.
Anyone faced the same issue and resolved? Please help.

Best Answer

As per Salesforce documentation:

If multiple spaces are required for some reason (e.g. formatting purposes), the &nbsp; entity must be used. However, in order for this entity to not itself be HTML escaped by apex, a proper "escape" option must be specified. Examples:

a) For the outputText tag, the "escape" attribute must be set to false. e.g.:

Controller:

comment = new CaseComment(CommentBody = 'There&nbsp;&nbsp;&nbsp;are&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;spaces&nbsp;&nbsp;&nbsp;between&nbsp;&nbsp;&nbsp;each&nbsp;&nbsp;&nbsp;word.\r\n\r\nThere is a blank line before this one.');

Apex page:

<apex:outputText escape="false" value="{!comment.CommentBody}"/>

b) selectList / selectOptions / selectOption:

If you wish to render non-breakable spaces in options in a select list, the attribute to set is a bit different; either by setting "itemEscaped" to "false" when using apex:selectOption, or, if creating SelectOption objects in the controller, call setEscapeItem(false) on each SelectOption that has the values with the &nbsp; entities.

Source: -https://help.salesforce.com/HTViewSolution?id=000194152&language=en_US

Update

I tried with following code and it is working fine with escape="false".

Controller

public String getMyText() {
    String myText = 'A&nbsp;&nbsp;&nbsp;B';
    return myText;
}

VF Page

Output

A B

Related Topic