How To Customize Live-Previews With DecapCMS

Published on November 25, 2024

Sujata Chaudhary Sujata Chaudhary

DecapCMS provides amazing versatility for managing content, but sometimes we need customizable live previews to meet the specific requirements of our websites. Live previews allow us to get a glimpse of how the content will look before publishing.

This blog explains how to set up and configure custom live previews.

Step-by-Step Tutorial for Setting Up Custom Live Previews

To render a site, we need HTML and CSS, but for custom live previews (which may have multiple templates), we also need JavaScript to determine which HTML and CSS to display.

After successfully configuring DecapCMS for your website, you’ll notice an admin folder containing index.html and config.yml. These files are crucial for enabling live previews.

DecapCMS provides two methods to create custom previews:

  1. registerPreviewTemplate
  2. registerPreviewStyle

1. Set Layouts Using registerPreviewTemplate

First, create a preview-templates folder (you can name it anything). Inside this folder, create a JavaScript file for your preview template, e.g., post.js. Export a function that returns the HTML structure for your preview. For example:

This is a sample layout for a “Page” collection. You can customize it to fit your requirements. Also the following is the code for page collection in config.yml file. We need to add the layout field for it to work.

Next, link this template in your admin/index.html file:

We are all set for the layouts. Now we need to setup the css for our previews.

2. Configure CSS Using registerPreviewStyle

At this stage, there are no styles applied to the preview. If your project already has styles in a Sass folder (for example, in a Jekyll project), you don’t need to write them again for live previews. Instead, you can use registerPreviewStyle to apply your global CSS.

Jekyll compiles Sass into pure CSS, which is then used in your site. Locate the compiled CSS file in the “_site/assets/css” folder. If it doesn’t exist, configure your Jekyll project to store the CSS during the build process.

To compile and use your CSS for live previews:

  1. Create a main.scss file in [project_folder]/assets/css/main.scss.
  2. Import your base index.scss file (or equivalent) into main.scss like this:

After building the project, you’ll find a main.css file in _site/assets/css. Use this file as the global CSS for your live previews.

Add the following code to admin/index.html:

Congratulations! Your live preview is now fully functional. It uses the specified CSS and renders content according to your customizations.

Previous Home