@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.

Upgrade your version

Are you on version 1 of @prismicio/helpers? Follow our instructions to upgrade to version 2.

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
npm
Copy
npm install @prismicio/helpers
Yarn
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 repositoryName = 'your-repository-name'
const client = prismic.createClient(repositoryName, { 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 repositoryName = 'your-repository-name'
const client = prismic.createClient(repositoryName, { 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.

asImageSrc()

Copy
asImageSrc(field)
asImageSrc(field, params)

asImageSrc() accepts an image field or one of its responsive views and returns its URL.

Copy
prismicH.asImageSrc(document.data.example_image)
// https://images.prismic.io/repo/image.png?auto=format,compress

Image transformations, like resizing or cropping, can be applied by passing options to the params parameter. Any of Imgix’s URL API parameters are supported (see Imgix’s URL API reference for a complete list).

In the following example, the sat: -100 parameter converts the image to grayscale by desaturating the image by 100%.

Copy
prismicH.asImageSrc(document.data.example_image, { sat: -100 })
// https://images.prismic.io/repo/image.png?auto=format,compress&sat=-100

By default, all image URLs from Prismic apply the auto=format,compress URL parameter to automatically optimize the image. This can be removed by setting the parameter to undefined, like so:

Copy
prismicH.asImageSrc(document.data.example_image, { auto: undefined })
// https://images.prismic.io/repo/image.png

If the image field is empty, asImageSrc() returns null.

Copy
prismicH.asImageSrc(document.data.empty_image)
// null

asImageWidthSrcSet()

Copy
asImageWidthSrcSet(field)
asImageWidthSrcSet(field, params)

asImageWidthSrcSet() accepts an image field or one of its responsive views and returns an object containing its URL and a width-based srcset attribute value. These values can be passed to <img> or <source> elements.

To learn more about srcset and its variations, see MDN’s Responsive Images guide.

Copy
prismicH.asImageWidthSrcSet(document.data.example_image)
// {
//   src:    'https://images.prismic.io/repo/image.png',
//   srcset: 'https://images.prismic.io/repo/image.png?width=640 640w, ' +
//           'https://images.prismic.io/repo/image.png?width=828 828w, ' +
//           'https://images.prismic.io/repo/image.png?width=1200 1200w, ' +
//           'https://images.prismic.io/repo/image.png?width=2048 2048w, ' +
//           'https://images.prismic.io/repo/image.png?width=3840 3840w'
// }

If the image field contains responsive views, they will automatically be used for each item in the srcset.

Copy
prismicH.asImageWidthSrcSet(document.data.example_image)
// {
//   src:    'https://images.prismic.io/repo/base.png',
//   srcset: 'https://images.prismic.io/repo/base.png?width=2400 2400w, ' +
//           'https://images.prismic.io/repo/mobile.png?width=500 500w, ' +
//           'https://images.prismic.io/repo/tablet.png?width=650 650w, ' +
//           'https://images.prismic.io/repo/desktop.png?width=1200 1200w'
// }

If the image field does not contain responsive views, the following widths will be used by default: 640w, 828w, 1200w, 2048w, 3840w. To override the widths, provide a widths parameter.

Copy
prismicH.asImageWidthSrcSet(document.data.example_image, {
  widths: [200, 600],
})
// {
//   src:    'https://images.prismic.io/repo/image.png',
//   srcset: 'https://images.prismic.io/repo/image.png?width=200 200w, ' +
//           'https://images.prismic.io/repo/image.png?width=600 600w'
// }

Image transformations, like resizing or cropping, can be applied by passing options to the params parameter. Any of Imgix’s URL API parameters are supported (see Imgix’s URL API reference for a complete list).

In the following example, the sat: -100 parameter converts the image to grayscale by desaturating the image by 100%.

Copy
prismicH.asImageWidthSrcSet(document.data.example_image, { sat: -100 })
// {
//   src:    'https://images.prismic.io/repo/image.png?sat=-100',
//   srcset: 'https://images.prismic.io/repo/image.png?sat=-100&width=640 640w, ' +
//           'https://images.prismic.io/repo/image.png?sat=-100&width=828 828w, ' +
//           'https://images.prismic.io/repo/image.png?sat=-100&width=1200 1200w, ' +
//           'https://images.prismic.io/repo/image.png?sat=-100&width=2048 2048w, ' +
//           'https://images.prismic.io/repo/image.png?sat=-100&width=3840 3840w'
// }

If the image field is empty, asImageWidthSrcSet() returns null.

Copy
prismicH.asImageWidthSrcSet(document.data.empty_image)
// null

asImagePixelDensitySrcSet()

Copy
asImagePixelDensitySrcSet(field)
asImagePixelDensitySrcSet(field, params)

asImagePixelDensitySrcSet() accepts an image field or one of its responsive views and returns an object containing its URL and a pixel-density-based srcset attribute value. These values can be passed to <img> or <source> elements.

To learn more about srcset and its variations, see MDN’s Responsive Images guide.

Copy
prismicH.asImagePixelDensitySrcSet(document.data.example_image)
// {
//   src:    'https://images.prismic.io/repo/image.png',
//   srcset: 'https://images.prismic.io/repo/image.png?dpr=1 1x, ' +
//           'https://images.prismic.io/repo/image.png?dpr=2 2x, ' +
//           'https://images.prismic.io/repo/image.png?dpr=3 3x'
// }

The following pixel densities will be used by default: 1x, 2x, 3x. To override the pixel densities, provide a pixelDensities parameter.

Copy
prismicH.asImagePixelDensitySrcSet(document.data.example_image, {
  pixelDensities: [2, 4],
})
// {
//   src:    'https://images.prismic.io/repo/image.png',
//   srcset: 'https://images.prismic.io/repo/image.png?dpr=2 2x, ' +
//           'https://images.prismic.io/repo/image.png?dpr=4 4x'
// }

Image transformations, like resizing or cropping, can be applied by passing options to the params parameter. Any of Imgix’s URL API parameters are supported (see Imgix’s URL API reference for a complete list).

In the following example, the sat: -100 parameter converts the image to grayscale by desaturating the image by 100%.

Copy
prismicH.asImagePixelDensitySrcSet(document.data.example_image, { sat: -100 })
// {
//   src:    'https://images.prismic.io/repo/image.png?sat=-100',
//   srcset: 'https://images.prismic.io/repo/image.png?sat=-100&dpr=1 1x, ' +
//           'https://images.prismic.io/repo/image.png?sat=-100&dpr=2 2x,' +
//           'https://images.prismic.io/repo/image.png?sat=-100&dpr=3 3x'
// }

If the image field is empty, asImagePixelDensitySrcSet() returns null.

Copy
prismicH.asImagePixelDensitySrcSet(document.data.empty_image)
// null

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? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.