跳转到正文

环境

有时需要仅在区块于 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);
}

区块标签始终会渲染前端标记,因此在由区块标签渲染的区块内,这两个函数都会返回 false,与 $isEditor 和 $isPreview 一样。