Template Content

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

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

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

  • Install the @prismicio/client in your project. Read the setup guide to learn more.
  • 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:

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

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"

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:

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:

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:

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.

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"

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.

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.

const serializer = (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/client kit. Here’s an example of how to use the asLink() method:

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:

`<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:

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"

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:

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.

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:

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.