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