Rendering Rich Text

As with all other Field Types, Brightspot renders a Rich-Text Element through a View Model. Brightspot stores rich-text elements as Strings, and a ViewModel’s simple getter for a String retrieves the text as it is stored. If Mary says to Henry in plain text, “No, Henry, I simply will not marry you!”, Brightspot stores her refusal as

No, Henry, I simply will not marry you!

and renders it the same way.

However, if Mary wants to put some emphasis into her refusal, she may say,

No, Henry, I simply will not marry you!

To render the previous string with boldface and italics, Brightspot needs to store HTML markup along with the plain text as in the following example:

No, Henry, I simply <i>will not</i> marry <b>you<b>!

However, Brightspot returns strings as they are stored. If you apply a simple getter to the above string, Brightspot escapes the opening and closing brackets so they appear in the rendered page. Looking at the string’s source, you see all the escape codes.

No, Henry, I simply &lt;i&gt;will not&lt;/i&gt; marry &lt;b&gt;you&lt;/b&gt;!

Brightspot provides the RichTextViewBuilder class to revert the escaped HTML to unescaped HTML so that the browser renders the rich text as expected.

Step 1: Create a Rich-Text Marker

Create a rich-text marker interface RichTextElementView.

package content.article;

public interface RichTextElementView {

}

Brightspot uses implementations of this interface to create Views.

Step 2: Add Rich-Text Support to ViewModel

Apply the method RichTextViewBuilder#buildHtml to the escaped HTML.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package content.article;

import com.psddev.cms.rte.RichTextViewBuilder;
import com.psddev.cms.view.ViewModel;
import com.psddev.cms.view.PageEntryView;
import styleguide.content.article.ArticleView;

public class ArticleViewModel extends ViewModel<Article> implements ArticleView, PageEntryView {

    @Override
    public CharSequence getBody() {
        return RichTextViewBuilder.buildHtml(
            model.getBody(),
            e -> createView(RichTextElementView.class, e));
    }

    /* Other getters */

}

In the previous snippet, the method buildHtml performs the following steps:

  1. Line 13 retrieves the escaped HTML stored in Brightspot.
  2. Line 14 calls the method createView to convert the escaped HTML into a View using the marker class RichTextElementView created in Step 1.