html code

How to present a list of text with bolded information sourced from Apex code

Problem

In our scenario, I need to display a list of text in our Visualforce page. Some part of the text needs to be bold. I will explain this with the below simple but not working example:

page:

<apex:page controller="TestListOutputController">
    <apex:repeat var="ot" value="{!outText}" >
        <div>
            {!ot}
        </div>
    </apex:repeat>
</apex:page>

Controller:

public class TestListOutputController 
{
    public List<String> outText {get; set;}
    public TestListOutputController()
    {
        outText = new List<String>();
        outText.add('Hello <Strong>World</Strong>');
        outText.add('Sample <Strong>Text</Strong>');
    }
}

Obviously the strong tag here doesn’t work. I can walk around this if the number of bold blocks is fixed. However, what if it is something like a blog section, or a stackexchange answer section? How should I handle such situations?

Answer

If you want to enable markup, use an <apex:outputText> with the escape attribute set to false.

<apex:outputText escape="false" value="Hello <strong>world</strong>!" />

Be aware, though, that if you are trying to use this attribute in a managed package, it will likely cause you to fail security review.