Rich Text Templating with Javascript

The Rich Text field (formerly called Structured Text) is a configurable text field with formatting options. This field provides content writers with a WYSIWYG editor where they can define the text as a header or paragraph, make it bold, add links, etc.

Output as HTML

The basic usage of the Rich Text field is to use the PrismicDOM.RichText object along with the asHtml method to transform the field into HTML code.

The following is an example that would display the title of a blog post.

Copy
var PrismicDOM = require('prismic-dom');

PrismicDOM.RichText.asHtml(document.data.title, ctx.linkResolver)

In the previous example when calling the asHtml method, you need to pass in a Link Resolver function. To learn more about how to set up a Link Resolver, check out our Link Resolving page.

Customizing the HTML output

You can customize the HTML output by passing an HTML serializer to the method. You can learn more about this on the HTML Serializer page.

Here is an example of an HTML serializer function that doesn't wrap images in a paragraph element and adds a custom class to all hyperlinks.

Copy
var PrismicDOM = require('prismic-dom');

var htmlSerializer = function (element, content) {
  
  // Don't wrap images in a <p> tag
  if (element.type == "image") {
    return '<img src="' + element.url + '" alt="' + element.alt + '">';
  }

  // Add a class to hyperlinks
  if (element.type == "hyperlink") {
    return '<a class="some-link" href="' + element.url + '">' + content + '</a>';
  }

  // Return null to stick with the default behavior
  return null;
};
var html = PrismicDOM.RichText.asHtml(doc.data.body, ctx.linkResolver, htmlSerializer);

Output as plain text

The asText method will convert and output the text in the Rich Text field as a string.

Copy
var PrismicDOM = require('prismic-dom');

PrismicDOM.RichText.asText(document.data.author)