Advanced Templating

In this article, we will teach you how to customize the output of Rich Text content in your Express app with an HTML Serializer function.


HTML Serializer

You can customize the HTML output of a Rich Text or Title field with a custom HTML Serializer.

An HTML Serializer defines how Rich Text content should be interpreted in your code. For instance: by default, italicized text will be rendered inside <em> tags, but you could use an HTML Serializer to specify that italicized text should instead be rendered inside <i> tags.

If your project is configured with Prismic, it will already have a default HTML Serializer integrated. If you would like to add custom formatting, you can add a custom HTML Serializer as needed.

Further Learning

Learn more about HTML Serializing in the HTML Serializer article.

Add a custom HTML Serializer function

To modify the HTML output of a Rich Text, create an HTML Serializer function. This function will identify the element by its type and return the desired output.

To create an HTML Serializer, Create the file config/htmlSerializer.js and paste in the following code.

Copy
import * as prismicH from '@prismicio/helpers'

const htmlSerializer = (type, element, content, children) => {
  // @prismicio/helpers includes a list of all element types
  if (type === prismicH.Element.paragraph) {
    // Add a custom class to paragraph elements
    return `<p class="example-class">${children}</p>`
  }
  // Else, return null
  return null
}

export default htmlSerializer

This serializer will add example-class to all paragraph elements.

Use the serializer function

Import htmlSerializer.js to index.js, and add the htmlSerializer variable in locals to access them in templates.

Copy
import htmlSerializer from './config/htmlSerializer.js'

app.use((req, res, next) => {
  res.locals.ctx = {
    prismicH,
    htmlSerializer,
  }
  next()
})

Now, pass htmlSerializer into a RichText component that renders a Rich Text field. Make sure to pass it in as the third parameter, the first being the content field and the second being the optional Link Resolver.

Here is an example passing the htmlSerializer into a RichText component:

Copy
<%- ctx.prismicH.asHTML(document.data.example_rich_text, null, ctx.htmlSerializer) %>

Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Get in touch with us on our Community Forum.