Template Slices

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 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/client kit to render the title and rich text field:

Copy
// 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>
`
*/

Can't find what you're looking for?

Need technical Support? Spot an error in the documentation? Get in touch with us on our Community Forum.