Environment
Sometimes it is necessary to show content in your blocks exclusively when it is being rendered inside the Gutenberg editor and not on the frontend. This technique is very useful to provide users with helpful information and placeholders if the necessary data hasn’t been input yet.
Editor
PHP
<?php if ($isEditor) : ?>
This content is only going to be rendered inside the editor.
<?php else : ?>
This content is only going to be rendered on the frontend.
<?php endif; ?>
Twig
{% if isEditor %}
This content is only going to be rendered inside the editor.
{% else %}
This content is only going to be rendered on the frontend.
{% endif %}
Preview
Blockstudio adds another environment variable that will come in handy for block developers. $isPreview allows you to conditionally render content inside the block preview window when hovering over a block inside the block inserter.
PHP
<?php if ($isPreview) : ?>
This content is only going to be rendered inside the block preview.
<?php else : ?>
This content is only going to be rendered on the frontend and editor.
<?php endif; ?>
Twig
{% if isPreview %}
This content is only going to be rendered inside the block preview.
{% else %}
This content is only going to be rendered on the frontend and editor.
{% endif %}
Outside templates
$isEditor and $isPreview exist only inside the template. Code that runs
during the same render but outside the template, such as a theme helper called
from a template or a filter like blockstudio/blocks/components/rich_text/render,
can call bs_is_editor() and bs_is_preview(). They return the same values the
template receives.
function theme_card_title(string $title): string {
if ($title === '' && bs_is_editor()) {
return '<span class="placeholder">Add a title</span>';
}
return esc_html($title);
}
Block tags always render frontend markup, so inside a block rendered from a
block tag both functions return false, as $isEditor and $isPreview do.