본문으로 건너뛰기

환경

블록이 프런트엔드가 아닌 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도 마찬가지입니다.