@prismicio/helpers - v2

Overview

@prismicio/helpers provide a set of helpers to render data from the Prismic API. These helpers help to render the following Prismic fields: Date, Timestamp, Link, Content Relationship, Rich Text, and Titles.

Dependencies

This package works with the Prismic API V2. Most Prismic users are on V2 by default. You can tell if you're using V2 if your endpoint URL includes prismic.io/api/v2.

Installation

  • npm
  • Yarn
Copy
npm install @prismicio/helpers
Copy
yarn add @prismicio/helpers

Example

In this example, we will use @prismicio/client to query content from a Prismic repository, and @prismicio/helpers to render the content we receive. (Note, this example also requires node-fetch to be installed as a dependency. See the @prismicio/client docs for more information on providing a fetch method.)

Copy
import * as prismic from '@prismicio/client'
import * as prismicH from '@prismicio/helpers'
import fetch from 'node-fetch' // Required if you're running this code in Node.js

const endpoint = prismic.getEndpoint('your-repo-name')
const client = prismic.createClient(endpoint, { fetch })

const init = async () => {
  const document = await client.getFirst('page')
  const documentAsHTML = prismicH.asHTML(document.data.description)
  console.log(documentAsHTML)
  // <p>This <em>should</em> log your formatted text.</p>
}

init()

Usage

This section assumes that you have required @prismicio/helpers in your project and stored it in the variable PrismicH and that you have queried a document from the Prismic API using the client method and stored it in a variable called document.

Copy
import * as prismic from '@prismicio/client';
import * as prismicH from '@prismicio/helpers';
import fetch from 'node-fetch' // Required in Node.js

const endpoint = prismic.getEndpoint('your-repo-name')
const client = prismic.createClient(endpoint, { fetch })

const init = async () => {
  const document = await client.getFirst('page');
  /*
  All operations happen here.
  */
}

init()

For the examples on this page, we'll assume the document has this structure:

Copy
{
  id: "YK_tSxAAACUAtaMT",
  uid: "example-document",
  type: "page",
  lang: "en-gb",
  alternate_languages: [ ],
  // document metadata
  // ...
  data: {
    example_title: [ … ], // A Title field
    example_rich_text: [ … ],// A Rich Text field
    example_date: "2021-05-27",// A Date field
    example_timestamp: "2021-05-26T22:00:00+0000",// A Timestamp field
    example_link: {...} // A Link field
   }
 }

@prismicio/helpers offer the following methods for rendering HTML.

asDate(field)

prismicH.asDate(field) takes a Date or Timestamp field from Prismic and converts it to a JavaScript date object.

Date and Timestamp fields from Prismic are strings, formatted as 2020-11-19 and 2020-11-19T16:45:39+0000 respectively. This method converts the string to a JavaScript date object. To learn more about JavaScript Date objects, see the MDN Date documentation or this tutorial by Tania Rascia.

Copy
const date = prismicH.asDate(document.data.example_date)

// date is a Date object with to the field's value
console.log(date.toISOString())
// 2018-01-16T13:46:15.000Z

console.log(date.getFullYear())
// 2018

asLink(field[, linkResolver])

prismicH.asLink(field[, linkResolver]) takes a Content Relationship field, Link field, or complete document from Prismic and an optional Link Resolver function and returns a URL. The Link Resolver function is only necessary if you are not using the Route Resolver. (See a comparison of the Link Resolver and Route Resolver.)

Copy
const linkResolver = (doc) => {
 if (doc.type === 'post') {
  return `/blog/${doc.uid}/`
 } else {
   return `/${doc.uid}`
 }
}

prismicH.asLink(document.data.example_link, linkResolver)
// /blog/peace-on-earth

asHTML(field[, linkResolver[, htmlSerializer]])

prismicH.asHTML(field[, linkResolver[, htmlSerializer]]) takes a Rich Text or Title field from the Prismic API, an optional Link Resolver function, and an optional HTML Serializer function. It returns HTML.

Copy
prismicH.asHTML(document.data.example_rich_text)
// <p>Lorem ipsum dolor sit <span class="codespan">amet</span>, consectetur adipiscing elit.</p><p>Ut enim ad minim veniam.</p>

prismicH.asHTML(field[, linkResolver[, htmlSerializer]]) has a built-in HTML Serializer with sensible defaults. If you provide an HTML Serializer, it will override the defaults selectively. If the provided HTML Serializer returns null, the built-in HTML Serializer will kick in.

Here's an example with an HTML Serializer:

Copy
const htmlSerializer = {
  label: ({ children, node }) => {
    if (node.data.label === 'codespan')
      return `<code>${children}</code>`;
  }
};

prismicH.asHTML(
  document.data.example_rich_text, 
  null, 
  htmlSerializer
);
// <p>Lorem ipsum dolor sit <code>amet</code>, consectetur adipiscing elit.</p><p>Ut enim ad minim veniam.</p>

To learn how to create an HTML Serializer, see the HTML Serializer documentation.

asText(field[, separator])

prismicH.asText(field[, separator]) accepts a Rich Text or Title field from the Prismic API and an optional separator and converts it to plain text string. The separator is a string that joins block-level elements, and it defaults to a space, " ".

Copy
prismicH.asText(document.data.example_rich_text)
// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut enim ad minim veniam.

prismicH.asText(document.data.example_rich_text, '\n\n')
// Lorem ipsum dolor sit amet, consectetur adipiscing elit.
//
// Ut enim ad minim veniam.

isFilled

prismicH.isFilled is an object containing small functions that determine if a field has a value.

Copy
prismicH.isFilled.link(document.data.example_link)
// `true` if `example_link` contains a link, `false` otherwise.

The isFilled helpers can be used to display fallback content:

Copy
if (prismicH.isFilled.title(document.data.example_title)) {
  return `<h1>${document.data.example_title}</h1>`
} else {
  return "<h1>Untitled</h1>"
}

A function is provided for each primitive field type:

  • color(field)
  • contentRelationship(field)
  • date(field)
  • embed(field)
  • geoPoint(field)
  • image(field)
  • imageThumbnail(field) - A thumbnail within an Image field.
  • integrationFields(field)
  • keyText(field)
  • link(field)
  • linkToMedia(field)
  • number(field)
  • richText(field)
  • select(field)
  • timestamp(field)
  • title(field)

A function is provided for each composite field type as well:

  • group(field) - A Group field is filled if it contains at least one item.
  • sliceZone(slices) - A Slice Zone is filled if it contains at least one Slice.

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.