Pereiti prie turinio

Aplinka

Kartais turinį blokuose reikia rodyti tik tada, kai jie atvaizduojami Gutenberg redaktoriuje, o ne išorinėje sąsajoje. Šis būdas labai naudingas, kai norite pateikti naudotojams pagalbinės informacijos ir vietaženklių, jei reikiami duomenys dar neįvesti.

Redaktorius

PHP

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

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 %}

Peržiūra

Blockstudio prideda dar vieną aplinkos kintamąjį, naudingą blokų kūrėjams. $isPreview leidžia sąlygiškai atvaizduoti turinį bloko peržiūros lange, užvedus žymeklį ant bloko įterpimo lange.

PHP

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

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 %}

Už šablonų ribų

$isEditor ir $isPreview pasiekiami tik šablone. Kodas, vykdomas to paties atvaizdavimo metu, bet už šablono ribų, pavyzdžiui, iš šablono iškviesta temos pagalbinė funkcija arba filtras, toks kaip blockstudio/blocks/components/rich_text/render, gali iškviesti bs_is_editor() ir bs_is_preview(). Jos grąžina tas pačias reikšmes, kurias gauna šablonas.

PHP
function theme_card_title(string $title): string {
  if ($title === '' && bs_is_editor()) {
    return '<span class="placeholder">Add a title</span>';
  }

  return esc_html($title);
}

Blokų žymos visada atvaizduoja priekinės dalies žymėjimą, todėl bloke, atvaizduojamame iš bloko žymos, abi funkcijos grąžina false, kaip ir $isEditor bei $isPreview.