Craft CMS: Hide Content In Live Preview Mode

There are some circumstances in which a developer might want to hide certain elements of their Twig templates from appearing in Craft's live preview mode.

Recently I started encountering a weird error with the Disqus comments boxes on each of this site's pages in which comments were being duplicated across several pages.

After a little research I discovered that Disqus will attach the thread id (which I was setting as the slug of the article) to the URL upon which it first appears.

Because I was using live preview whilst writing these posts this resulted in Disqus linking multiple different article slugs to some internal live preview URL used by Craft.

This error is a documented problem with Disqus as the same thing happens when using live previews in Wordpress.

I figured the best course of action would be to just disable comments entirely when in live preview mode, and it turns out it's really simple.

{% if not craft.app.request.isLivePreview %}
 {# Content here won't show in live preview #}
{% endif %

Super easy.

This is also useful if you have an element on your page that changes height after the initial page load. In my expereience this causes live preview to gradually scroll down the page until you're just left looking at your site's footer.

It's worth having a look through the documentation for craft.app.request to see what other info you have access to in both your templates and plugin code. You never know when you might need to check whether a request was sent specifically from a Flash application ¯\_(ツ)_/¯


Read Next



2024 Goals
Write Things