Template Slices

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.

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.

The page assumes you have queried a document from the Prismic API and stored it in a variable called doc.

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.

Create a Slice in Prismic

In Prismic, your Slices are managed in your Custom Type model. To learn how to model a Custom Type, see the content modeling docs.

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/helpers kit to render the Title and Rich Text field:

// Example SliceZone.js file

import * as prismicH from '@prismicio/helpers'

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 + prismicH.asHTML(slice.primary.sample_text)

      return ''
}, '')

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

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.