跳转到正文

RichText

RichText 编辑内容会立即存储在区块的属性中,并纳入 Gutenberg 的撤销和重做历史记录,包括重复器行中的 RichText。选中多个区块时保存,会保留每个区块各自的内容和属性。

RichText 组件允许在编辑器中渲染可编辑输入框,并在前端渲染静态的 HTML 元素。它基于 RichText 组件WordPress提供。

基本用法

要以最基本的形式使用 RichText,你需要向 block.json 添加相应属性,并将 RichText 组件添加到区块中。

JSON
{
  "$schema": "https://blockstudio.dev/schema/block",
  "name": "blockstudio/rich-text",
  "title": "Native Block",
  "category": "text",
  "icon": "star-filled",
  "description": "Native Blockstudio RichText block.",
  "blockstudio": {
    "attributes": [
      {
        "id": "myRichText",
        "type": "richtext"
      }
    ]
  }
}
PHP
<RichText attribute="myRichText" />

你可以在区块中使用任意数量的 RichText 组件。

属性

allowedFormats

你可以使用 allowedFormats 属性限制 RichText 组件中可用的格式。

PHP

PHP
<RichText attribute="myRichText" allowedFormats="<?php echo esc_attr(wp_json_encode(['core/bold', 'core/italic'])); ?>" />

Twig

Twig
<RichText attribute="myRichText" allowedFormats="{{ ['core/bold', 'core/italic']|json_encode|escape('html_attr') }}" />

占位符

你可以使用 placeholder 属性为 RichText 组件设置占位符。

PHP
<RichText attribute="myRichText" placeholder="Enter some text" />

preserveWhiteSpace

是否保留值中的空白字符。通常,制表符、换行符和空格会合并为单个空格。启用后,软换行会保存为换行符,而不是换行元素。

PHP
<RichText attribute="myRichText" preserveWhiteSpace="true" />

标签

默认情况下,RichText 内容会渲染在 p 元素中。你可以使用 tag 属性更改此设置。

PHP
<RichText attribute="myRichText" tag="h1" />

withoutInteractiveFormatting

默认情况下会显示所有格式控件。此设置可用于移除会使内容具有交互性的格式控件。

PHP
<RichText attribute="myRichText" withoutInteractiveFormatting="true" />

重复器字段

RichText 可在重复器字段中使用。使用带循环索引的方括号表示法来指定正确的行。

JSON
{
  "blockstudio": {
    "attributes": [
      {
        "id": "items",
        "type": "repeater",
        "attributes": [
          {
            "id": "heading",
            "type": "richtext"
          }
        ]
      }
    ]
  }
}
PHP
<?php foreach ($a['items'] as $index => $item) : ?>
  <RichText tag="h2" attribute="items[<?php echo $index; ?>].heading" placeholder="Enter heading" />
<?php endforeach; ?>
Twig
{% for item in a.items %}
  <RichText tag="h2" attribute="items[{{ loop.index0 }}].heading" placeholder="Enter heading" />
{% endfor %}

attribute 值遵循 repeaterId[index].fieldId 模式,其中 index 是循环中的从零开始的行号。