Template Content

This technology has no Slice Machine integration

This framework has no integration with Prismic's developer tool, Slice Machine. You can still build a Prismic website with this technology by using Prismic's Legacy Builder. However, if you're starting a new project with Prismic, we strongly recommend using a technology that integrates with Slice Machine: Next.js or Nuxt.

This section will teach you how to template content from Prismic in a JavaScript app.

Before your proceed

We strongly recommend building your app with a JavaScript framework, like Express, React, or Vue. If you choose to use vanilla JavaScript, you'll first need a project configured with Prismic. If you don't have one yet, start with the Setup step.

This page assumes that you have already imported @prismicio/client as prismic (as specified in the setup step), and that you have queried a document from the Prismic API and stored it in a variable called prismicDoc.

Before you start to template your content, you must complete the following steps:

  1. Install the @prismicio/client in your project. Read the setup guide to learn more.
  2. Retrieve a document from the Prismic API and store it in a variable.

Intro to templating

Prismic content comes in more than a dozen field types. Most of these are primitive values, like numbers or booleans. Others are more complex structured values; these are: geopoint, embed group, image, title, rich text, and links.

Below we will explain how you can template each of these fields in your application.

Simple value fields

There are eight simple value fields in Prismic: boolean, color, key text, number, select, date, timestamp, UID.

You can directly template them in your application. Here are examples of simple fields rendered inside <span> tags:

Copy
`<span>${prismicDoc.data.example_boolean}</span>`
// Output: <span>true</span>

`<span>${prismicDoc.data.example_color}</span>`
// Output: <span>#a24196</span>

`<span>${prismicDoc.data.example_key_text}</span>`
// Output: <span>Lorem ipsum</span>

`<span>${prismicDoc.data.example_number}</span>`
// Output: <span>7</span>

`<span>${prismicDoc.data.example_select}</span>`
// Output: <span>Lorem impsum</span>

Date and timestamp

The date and timestamp fields are delivered as strings. Use the asDate() method from the @prismicio/client kit to save the timestamp or date field value as a JavaScript date object. Then you can format it using JavaScript's built-in date methods, like toLocaleDateString() function.

  • Date
  • Timestamp
Date
Copy
const rawPrismicDate = prismicDoc.data.example_date

console.log(rawPrismicDate)
// Output: "2021-10-22"

const javaScriptDate = prismic.asDate(rawPrismicDate)

console.log(javaScriptDate)
// Output: "Thu Oct 21 2021 19:00:00 GMT-0500 (Central Daylight Time)"

const formattedDate = javaScriptDate.toLocaleDateString()

console.log(formattedDate)
// Output: "21/10/2021"
Timestamp
Copy
const rawPrismicTimestamp = prismicDoc.data.example_timestamp

console.log(rawPrismicTimestamp)
// Output: "2021-10-22T05:00:00+0000"

const javaScriptDate = prismic.asDate(rawPrismicTimestamp)

console.log(javaScriptDate)
// Output: Fri Oct 22 2022 00:00:00 GMT-0500 (Central Daylight Time)

const formattedTimestamp = javaScriptDate.toLocaleDateString()

console.log(formattedTimestamp)
// Output: "22/10/2021"

Learn more about the asDate() method in the @prismicio/client Technical Reference.

Geopoint

The geopoint field is served as an object with two properties: latitude and longitude. Access these properties directly:

Copy
const { latitude, longitude } = prismicDoc.data.example_geopoint

const text = `My location is ${latitude}, ${longitude}.`

console.log(text)
// Output: "My location is 48.85392410000001, 2.2913515000000073."

Embed

You can template an embed field using the html value from the response:

Copy
const rawEmbed = prismicDoc.data.example_embed.html

console.log(rawEmbed)
// Outputs an HTML iframe element

Group

To template a group, you can use a reduce() function to loop over the results. Here's a usage example:

Copy
const itemList = prismicDoc.data.example_group.reduce(
  (previousItems, currentItem) =>
    previousItems + `<li>${currentItem.example_key_text_in_group}</li>`,
  ''
)

console.log(itemList)
// Output: '<li>This is some text in a group.</li><li>And here we have more text in a group.</li><li>Finally another piece of text in a group.</li>'

Rich text and title

Rich text and title fields are delivered in an array that contains information about the text structure. To render HTML for your rich text, use the asHTML() method. To render plain text, with no markup, use the asText() method.

  • Rich text
  • Title
Rich text
Copy
import * as prismic from '@prismicio/client'

const contentHTML = prismic.asHTML(prismicDoc.data.example_rich_text)

console.log(contentHTML)
//  Output: <p>Example Rich Text Value</p>

const contentText = prismic.asText(prismicDoc.data.example_rich_text)

console.log(contentText)
//  Output: "Example Rich Text Value"
Title
Copy
import * as prismic from '@prismicio/client'

const titleHTML = prismic.asHTML(prismicDoc.data.example_title)

console.log(titleHTML)
//  Output: <h1>Hello World</h1>

const titleText = prismic.asText(prismicDoc.data.example_title)

console.log(titleText)
//  Output: "Hello World"

Learn more about the rich text helper methods in the @prismicio/client Technical Reference.

You can customize the HTML output of a rich text field by passing a rich text serializer to the asHTML() method.

Copy
const contentText = prismic.asHTML(prismicDoc.data.example_rich_text, { serializer });

Here is an example use case of a rich text serializer. It will detect if the element had a codespan label and wrap it in a <code/> tag.

If the function doesn't match any case, it returns null and defaults to the built-in rich text serializer.

Copy
const htmlSerializer = (type, element, content, children) => {
  if (element.data?.label === 'codespan') {
    return `<code>${children.join('')}<code/>`
  }

  return null
}

Link and content relationship

There are two things that you might want to do with links and content relationships:

  • Link to another page or media item, internally or externally
  • Pull in content from another Prismic document

Render a link

Render links using the asLink() method from the @prismicio/client kit. Here's an example of how to use the asLink() method:

Copy
const internalLink = prismic.asLink(prismicDoc.data.example_internal_link);

const externalLink = prismic.asLink(prismicDoc.data.example_external_link);

console.log(internalLink)
// Output: "/post/first-post"

console.log(externalLink)
// Output: "https://prismic.io"

You can use the link in an a tag:

Copy
`<a href="${externalLink}">Get started with Prismic.</a>`

Pull in content from another document

When you link to another document in Prismic, the API response will include the metadata for that document. To get content for that document, you must use the graphQuery or fetchLinks option in your API query.

fetchLinks works by specifying the custom type and field that you would like to retrieve from linked documents. For instance, if you're listing blog posts, and you would like to get the name of the author linked on each blog post, your query would look like this:

Copy
client.getAllByType('blog_post', { fetchLinks: 'author.name' })

Then, the name property will appear on a data object on the link in the API result.

In the following example, we render a key text field from a content relationship:

Copy
const authorName = prismicDoc.data.author_link.data.name

console.log(authorName)
// Output: "Jane Doe"

Image

The image field returns an object with data about the image, including a URL for your image (hosted on Prismic's servers) and alt text. You can template an image using the asImageSrc() function and an <img> element:

Copy
import * as prismic from '@prismicio/client'

const src = prismic.asImageSrc(document.data.example_image)

const image = `
  <img
    src="${src}"
    alt="${document.data.example_image.alt}"
  />
`

Images can be transformed using Prismic’s built-in Imgix integration and asImageSrc(). This allows you to resize, crop, recolor, and more. See Imgix’s URL API Reference for a full list of available information.

The following example converts the image to grayscale with sat: -100.

Copy
import * as prismic from '@prismicio/client'

const src = prismic.asImageSrc(document.data.example_image, {
  sat: -100,
})

const image = `
  <img
    src="${src}"
    alt="${document.data.example_image.alt}"
  />
`

Image fields can have responsive views. Retrieve their URLs by passing each view to asImageWidthSrcSet().

The asImageWidthSrcSet() and asImagePixelDensitySrcSet() functions build responsive srcset attribute values that can be passed to <img> or <source> elements:

Copy
import * as prismic from '@prismicio/client'

const { src, srcset } = prismic.asImageWidthSrcSet(
  document.data.example_image
)

const image = `
  <img
    src="${src}"
    srcset="${srcset}"
    alt="${document.data.example_image.alt}"
  />
`

Learn more about the image helper methods in the @prismicio/client Technical Reference.


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.