Preview Mode
The Contao Managed Edition comes with an additional preview.php entry point. This entry point is either accessible via
a back end login, or a valid preview link.
When this entry point is accessed with a back end login, it offers features like logging in as a front end member or showing hidden elements.
To check whether code (content element, front end module, etc.) is currently executed within the preview entry
point you can check for the _preview request attribute.
class FoobarController extends AbstractContentElementController
{
protected function getResponse(Template $template, ContentModel $model, Request $request): Response
{
if ($request->attributes->get('_preview')) {
// Execute some code within the preview entry point
}
return $template->getResponse();
}
}{% if app.request.attributes._preview|default %}
{# Show some content within the preview entry point #}
{% endif %}This however, does not check for the actual preview mode, which is activated by selecting Unpublished: show in the
preview toolbar - or by accessing the preview entry with a valid preview link that has this feature enabled. To check
for this, you can use the TokenChecker service.
use Contao\CoreBundle\Security\Authentication\Token\TokenChecker;
class FoobarController extends AbstractContentElementController
{
public function __construct(private readonly TokenChecker $tokenChecker)
{
}
protected function getResponse(Template $template, ContentModel $model, Request $request): Response
{
if ($this->tokenChecker->isPreviewMode()) {
// Execute some code when the preview mode is active
}
return $template->getResponse();
}
}since 5.3 This is also available via the contao global Twig variable:
{% if contao.is_preview_mode %}
{# Show some content only available in the preview mode #}
{% endif %}