Templating Content

On this page, you'll learn how to template content from the Prismic API in your Next.js application.


ūüēô Before Reading

This article assumes that you have queried your API and saved the document object in a variable named document.

Simple Content Fields

These are simple content fields which you just need to render with their API ID. These are represented as either a string, a number, a category, or a boolean. Templating them is quite simple.

Fields

API ID

Color

my_color

Key Text

author_name

Number

example_number

select

select_category

Boolean

my_boolean

Here's a simple example of how to template the Number field value from its API ID. As mentioned in the above table, the Number field API ID is example_number. Just like this, you need to retrieve other fields in the table.

Copy
<span>{ document.data.example_number }</span>

Structured Content Fields

The remaining structured content types are:

  • Date
  • Timestamp
  • Geopoint
  • Embed
  • Group

Date and Timestamp

The raw response of these fields provides the following formats:

  • Date:¬†YYYY-MM-DD
  • Timestamp:¬†YYYY-MM-DDTHH:MM:SS+0000

Field

API ID

Date

example_date

Timestamp

event_date

Here's an example of how to retrieve the Date object and Timestamp object from a Date field and Timestamp field using the prismic-reactjs Date method. And convert them to a String using a toString method.

  • Date
  • Timestamp
Copy
import { Date } from 'prismic-reactjs'

const exampleDate = Date(document.data.example_date).toString;
// Date outputs as "2020-12-12" 
Copy
import { Date } from 'prismic-reactjs';

const eventDate = Date(document.data.event_date).toString;
// Timestamp outputs as "2020-12-12T06:00:00+0000"

Format the Date and Timestamp field

To format these fields, you can choose one of these options:

  1. Use a library such as date-fns-tz.
  2. The built-in DateTimeFormat method.

Here's an example of how to convert the Date or Timestamp object to a formatted string using date-fns-tz:

  • Date
  • Timestamp
Copy
import { Date } from 'prismic-reactjs';
import { format } from 'date-fns-tz'

const date = Date(document.data.example_date)
const displayDate = format(date),'MMMM dd, yyyy');
// Outputs as "December 12, 2020 
Copy
import { Date } from 'prismic-reactjs';
import { format } from 'date-fns-tz'

const eventDate = Date(document.data.event_date)
const formatedTimestamp = format(eventDate,'MMMM dd, yyyy H:mm a');
// Outputs as "December 12, 2020 12:00 PM"

The built-in DateTimeFormat method :

  • Date
  • Timestamp
Copy
import { Date } from 'prismic-reactjs';

const date = Date(document.data.example_date);

const formattedDate = Intl.DateTimeFormat('en-US',{
  year: 'numeric',
  month: 'short',
  day: '2-digit' }).format(date);
// Output in M d, Y format
Copy
import { Date } from 'prismic-reactjs';

const timestamp = Date(document.data.event_date);

const formattedTimestamp = Intl.DateTimeFormat('en-US',{
  year: "numeric",
  month: "short",
  day: "2-digit",
  hour: "numeric",
  minute: "2-digit",
  second: "2-digit"
}).format(timestamp);
// Outputs the date and time in Mon dd, YYYY, H:MM:SS AM/PM format

Geopoint

Here is an example of how to retrieve the latitude & longitude coordinates for a GeoPoint field. In this case, the API ID for the GeoPoint field is location.

Copy
const location = document.data.location;
 
const lat = location.latitude;  // latitude
const long = location.longitude; // longitude

Embed

This is the API response of the embed field.

Copy
"embed_video": {
  "version": "1.0",
  "url": "https://prismic.io",
  "type": "link",
  "title": "Make your website editable for the whole team - Prismic",
  "provider_name": null,
  "thumbnail_url": "https://images.prismic.io/prismic-website/6e49007fec52f99861047cdd55b3ab190ea04295_dev-landing-page-image.png?auto=compress,format",
  "html": "<div data-type=\"unknown\"><a href=\"https://prismic.io\"><h1>Make your website editable for the whole team - Prismic</h1>
  "embed_url": "https://prismic.io/"
},

You can template an embed field using the html from the response. In case, the API ID for the Embed field is embed_video.

Copy
// In a React component
render () {
  return <div dangerouslySetInnerHTML={{ __html: document.data.embed_video.html }} />
}

Images

In Prismic, you can define an image's alt text, copyright, and alternate crops ‚ÄĒ all of which can also have their own alt text. All of this information is served in the API response. A simple image field might look like this:

Copy
// document.data.example_image
{
  dimensions: {
    width: 1920,
    height: 1302
  },
  alt: null,
  copyright: null,
  url: "https://images.prismic.io/sm-20201204-2/7d1fba99-5bec-4d59-b8eb-402706e2d36c_a-pril-62u95KgB49w-unsplash.jpg?auto=compress,format"
},

You can template an image with the img element:

Copy
<img src={document.data.example_image.url} alt={document.data.example_image.alt} />

Rich Text and Titles

Rich Text and Titles are delivered in an array that contains information about the text structure. Here's an example of the API response of the Rich Text field (Title fields follow the same format):

Copy
// document.data.example_rich_text
[
  {
    type: "paragraph",
    text: "Example Rich Text Value",
    spans: [
      {
        start: 8,
        end: 17,
        type: "strong"
      }
    ]
  }
],

Rich Text Component

Here's how to render Rich Text or a Title with the rich text component:

Copy
<RichText render={document.data.example_rich_text} linkResolver={linkResolver} />

Rich Text Helper Function

The basic usage of the Rich Text / Title field is to use the RichText.render method to transform the field into HTML code.

Copy
{RichText.render(document.data.rich_text_example, linkResolver)}

Plaintext Helper Function

If a developer wants complete control of the style(CSS), the RichText.asText method will be useful because it converts and outputs the text as a string. Here is how to get plain text from a Rich Text or title field with the plaintext helper function:

Copy
{RichText.asText(document.data.author)}

Group

The group allows you to create repeatable content templates. Group fields are available in the main section of your document. A Group field renders an array of content groups:

Copy
// document.data.example_group
[
  {
    example_boolean_in_group: true,
    example_number_in_group: 3,
    example_key_text_in_group: "dog"
  },
  {
    example_boolean_in_group: false,
    example_number_in_group: 7,
    example_key_text_in_group: "cat"
  },
],

To template a Group, you can use a map function map():

Copy
<ul>
  {document.data.example_group.map((post, i) => (
    <li key={`post-${i}`}>
      {post.example_key_text}
      {post.example_number}
    </li>
  ))}
</ul>

ūüí° Further Learning: Content Types You can learn more about all of these content types in our Content Modeling documentation.


Related articles:


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.