コンテンツへスキップ

環境

ブロック内のコンテンツを、フロントエンドではなくGutenbergエディター内でレンダリングするときだけ表示したい場合があります。この方法は、必要なデータがまだ入力されていないときに、役立つ情報やプレースホルダーをユーザーに表示するのに便利です。

エディター

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

プレビュー

Blockstudioは、ブロック開発者に役立つ環境変数を追加します。$isPreviewを使うと、ブロックインサーター内でブロックにカーソルを合わせたとき、ブロックのプレビューウィンドウにコンテンツを条件付きで表示できます。

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

テンプレート外

$isEditorと$isPreviewはテンプレート内でのみ使用できます。テンプレートと同じレンダリング中に実行されるものの、テンプレート外で動作するコード(テンプレートから呼び出されるテーマヘルパーや、blockstudio/blocks/components/rich_text/renderのようなフィルターなど)では、bs_is_editor()とbs_is_preview()を呼び出せます。テンプレートと同じ値が返されます。

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);
}

ブロックタグは常にフロントエンドのマークアップをレンダリングするため、ブロックタグからレンダリングされたブロック内では、$isEditorと$isPreviewと同様に、両方の関数がfalseを返します。