Live Preview

Preview Mode

Detect when a page is rendered in preview mode. Works for templates, snippets, CSS, and JavaScript.

You may want to hide certain elements or disable certain features in preview mode. For example, you may want to hide the cookie banner in preview mode, or disable animations such as page transitions.

This can be done in your backend templates as well as in your frontend code.

Backend

The Kirby Live Preview provides a previewMode content key that you can use to detect whether the current page is in preview mode. The key is true if the page is in preview mode and undefined (false) otherwise:

if ($page->previewMode()->isTrue()) {
  // Page is in preview mode
}

Wrap the HTML in your snippets and template that you want to hide in a conditional statement that checks for the previewMode. For example, you can hide the cookie banner in preview mode:

site/snippets/footer.php
<?php if ($page->previewMode()->isFalse()): ?>
  <?php snippet('cookie-banner') ?>
<?php endif ?>

Frontend

The same page rendered as a preview embeds a data-preview-mode attribute in the document element (<html> tag). You can use this attribute to hide or disable elements in your frontend code.

For example, you can hide the cookie banner with the following CSS:

assets/css/main.css
[data-preview-mode] .cookie-banner {
  display: none;
}

For JavaScript animations or other features, you can use the data-preview-mode attribute to disable them:

assets/js/main.js
const isPreviewMode = document.documentElement.dataset.previewMode === "true";

if (!isPreviewMode) {
  // Run your animations or other features
}