Templating the Rich Text & Title fields
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. The Title field is a specific Rich Text field used for titles.
There are two different API Endpoints
Note that there are two different API Endpoints which are outputted in different ways.
If you are using the javascript-kit, then make sure you are using the the API v1 endpoint:
https://your-repo-name.cdn.prismic.io/api
If you are using the @prismicio/client and prismic-dom kits, then make sure you are using the API v2 endpoint:
https://your-repo-name.cdn.prismic.io/api/v2
The code snippets below are for the API v2.
The basic usage of the Rich Text / Title 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 retrieve the HTML for the title of a blog post. In this case, the Rich Text field has the API ID value of title.
var PrismicDOM = require('prismic-dom');
var titleHtml = PrismicDOM.RichText.asHtml(document.data.title, 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.
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.
Before Reading
In order for the following HTML Serializer example to work, you must make sure that your project is using the prismic-dom version 2.1.0 or higher. This will not work for older versions of the kit.
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 other paragraph elements.
In this example the Rich Text field has the API ID page_text.
var PrismicDOM = require('prismic-dom');
var Elements = PrismicDOM.RichText.Elements;
var htmlSerializer = function (type, element, content, children) {
switch(type) {
// Add a class to paragraph elements
case Elements.paragraph:
return '<p class="paragraph-class">' + children.join('') + '</p>';
// Don't wrap images in a <p> tag
case Elements.image:
return '<img src="' + element.url + '" alt="' + element.alt + '">';
// Return null to stick with the default behavior
default:
return null;
}
};
var html = PrismicDOM.RichText.asHtml(document.data.page_text, ctx.linkResolver, htmlSerializer);
The asText method will convert and output the text in the Rich Text & Title field as a string.
Here the Rich Text field has the API ID author.
var PrismicDOM = require('prismic-dom');
var authorText = PrismicDOM.RichText.asText(document.data.author)