Template Content
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 and @prismicio/helpers as prismic and prismicH respectively (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:
- Install the @prismicio/helpers in your project. Read the setup guide to learn more.
- Retrieve a document from the Prismic API and store it in a variable.
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.
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:
`<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>
The Date and Timestamp fields are delivered as strings. Use the asDate() method from the @prismicio/helpers 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
const rawPrismicDate = prismicDoc.data.example_date
console.log(rawPrismicDate)
// Output: "2021-10-22"
const javaScriptDate = prismicH.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"
const rawPrismicTimestamp = prismicDoc.data.example_timestamp
console.log(rawPrismicTimestamp)
// Output: "2021-10-22T05:00:00+0000"
const javaScriptDate = prismicH.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/helpers Technical Reference.
The GeoPoint field is served as an object with two properties: latitude and longitude. Access these properties directly:
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."
const rawEmbed = prismicDoc.data.example_embed.html
console.log(rawEmbed)
// Outputs an HTML iFrame element
To template a Group, you can use a reduce() function to loop over the results. Here's a usage example:
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 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
import * as prismicH from '@prismicio/helpers'
const contentHTML = prismicH.asHTML(prismicDoc.data.example_rich_text)
console.log(contentHTML)
// Output: <p>Example Rich Text Value</p>
const contentText = prismicH.asText(prismicDoc.data.example_rich_text)
console.log(contentText)
// Output: "Example Rich Text Value"
import * as prismicH from '@prismicio/helpers'
const titleHTML = prismicH.asHTML(prismicDoc.data.example_title)
console.log(titleHTML)
// Output: <h1>Hello World</h1>
const titleText = prismicH.asText(prismicDoc.data.example_title)
console.log(titleText)
// Output: "Hello World"
Learn more about the Rich Text helper methods in the @prismicio/helpers Technical Reference.
You can customize the HTML output of a Rich Text field by passing an HTML Serializer to the asHTML() method.
const contentText = prismicH.asHTML(prismicDoc.data.example_rich_text, null, htmlSerializer);
Here is an example use case of an HTML 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 HTML Serializer.
const htmlSerializer = (type, element, content, children) => {
if (element.data?.label === 'codespan') {
return `<code>${children.join('')}<code/>`
}
return null
}
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 links using the asLink() method from the @prismicio/helpers kit. Here's an example of how to use the asLink() method:
const internalLink = prismicH.asLink(prismicDoc.data.example_internal_link);
const externalLink = prismicH.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:
`<a href="${externalLink}">Get started with Prismic.</a>`
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:
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:
const authorName = prismicDoc.data.author_link.data.name
console.log(authorName)
// Output: "Jane Doe"
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:
import * as prismicH from '@prismicio/helpers'
const src = prismicH.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.
import * as prismicH from '@prismicio/helpers'
const src = prismicH.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:
import * as prismicH from '@prismicio/helpers'
const { src, srcset } = prismicH.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/helpers Technical Reference.
Was this article helpful?
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.