Render Slices
On this page, you'll learn how to template your document's slices in your Express.js project.
In Prismic, slices are repeatable, rearrangeable content sections of your webpage. On this page, you’ll learn how to template your document’s slices in your Express project.
Create slices in Prismic
In Prismic, navigate to the custom type that you’re developing (for instance, “page” or “blog_post”) and create slices. Learn more about slices in What is a Slice?
Setup
Inside your views/
directory, Create a slices/
directory. In your slices/
directory, create separate ejs
templates for each slice that you created in Prismic.
Each ejs
template will receive the slice
object as a prop.
Create a SliceZone
To template your array of slices, create a SliceZone.ejs
template in views/
. The template will receive your array of slices as a prop called SliceZone
.
Then, it will loop over the slices in the SliceZone
prop with a map()
function and render an EJS template with the data from each slice based on a conditional block that evaluates the slice type.
An example might help illustrate how this works:
Example
In our example, we have two slices: a text_slice
and an image_gallery_slice
. You can see what the API response for a slice zone looks like in Template Content.
In views/slices/
Create separate templates to render each slice field: TextSlice.ejs
and ImageGallery.ejs
.
In the API response, the content of the repeatable zone is found in the items
property and the content of the non-repeatable zone is inside the primary
property of the slice. Here’s how you might render different fields inside the ejs
templates:
<h3><%- slice.primary.key_text %></h3>
Here is what SliceZone.ejs
will look like:
<% getSlices = ((SliceZone) => {
return SliceZone.reduce((prevSlices, slice) => {
if (slice.slice_type === 'text_slice') {
return prevSlices + include('./slices/TextSlice.ejs', { slice: slice })
}
else if (slice.slice_type === 'image_gallery_slice') {
return prevSlices + include('./slices/ImageGallery.ejs', { slice: slice })
}
else {
return '<h1>No Slices found</h1>'
}
}, '')
}) %>
<%- getSlices(SliceZone) %>
Include the SliceZone on a page
Open the ejs
template where you would like to render your slices and add the SliceZone. This should be the page where you are passing your response from the query.
Including the SliceZone on page.ejs
:
<%- include('SliceZone', {SliceZone: document.data.body}) %>