Środowisko
Czasami treść w blokach powinna być widoczna wyłącznie podczas renderowania w edytorze Gutenberg, a nie na frontendzie. Ta technika przydaje się do wyświetlania użytkownikom pomocnych informacji i tekstów zastępczych, gdy nie wprowadzono jeszcze wymaganych danych.
Edytor
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 %}
Podgląd
Blockstudio dodaje kolejną przydatną zmienną środowiskową dla twórców bloków. $isPreview umożliwia warunkowe renderowanie treści w oknie podglądu bloku po najechaniu kursorem na blok w inserterze bloków.
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 %}
Poza szablonami
$isEditor i $isPreview istnieją tylko wewnątrz szablonu. Kod uruchamiany podczas tego samego renderowania, ale poza szablonem, na przykład pomocniczy kod motywu wywoływany z szablonu lub filtr taki jak blockstudio/blocks/components/rich_text/render, może wywołać bs_is_editor() i bs_is_preview(). Zwracają one te same wartości, które otrzymuje szablon.
function theme_card_title(string $title): string {
if ($title === '' && bs_is_editor()) {
return '<span class="placeholder">Add a title</span>';
}
return esc_html($title);
}
Tagi bloków zawsze renderują znacznikowanie frontendu, więc wewnątrz bloku renderowanego z poziomu tagu bloku obie funkcje zwracają false, podobnie jak $isEditor i $isPreview.