Template Slices

This page will teach you how to template slices in your Vanilla JavaScript project.

This page will teach you how to template slices in your JavaScript project. Slices are repeatable, rearrangeable content sections used to define a dynamic zone for richer page layouts.

The body property

If your Prismic document contains slices, they are stored by default in an array on the document object’s data property called body. Each slice object has a slice_type and the data for the slice.

Templating with reduce()

To template these slices, create a reduce() function that will loop over the array and render each slice based on a switch statement.

In the following example, we will work with two slices: one called text_slice and one called image_slice.

The reduce() method will read each element in the array of slices and return a string of HTML representing all of the slices. We’ll use the asHTML() method from the @prismicio/client kit to render the title and rich text field:

// Example SliceZone.js file

import * as prismic from "@prismicio/client";

const SliceZone = document.data.body.reduce(
  (previousSlices, slice) => {
    switch (slice.slice_type) {
      case "image_slice":
        return (
          previousSlices +
          `<img src="${slice.primary.example_image.url}" alt="${slice.primary.example_image.alt}" />`
        );

      case "text_slice":
        return (
          previousSlices +
          prismic.asHTML(slice.primary.sample_text)
        );

      default:
        return "";
    }
  },
  "",
);

/*
Output:
`
<img src="https://images.prismic.io/query-test/5ad4_prismiclogo.png?auto=compress,format" alt="Prismic logo" />
<p>Lorem impsum...</p>
`
*/