RichText
RichText の編集内容はブロックの属性に即座に保存され、リピーター行内の RichText を含め、Gutenberg の取り消し・やり直し履歴に反映されます。複数のブロックを選択した状態で保存しても、各ブロック固有のコンテンツと属性が保持されます。
RichTextコンポーネントを使うと、エディター内に編集可能な入力欄を、フロントエンドに静的なHTML要素をレンダリングできます。RichTextコンポーネントWordPressを基にしています。
基本的な使い方
RichTextを最も基本的な形で使うには、block.jsonに適切な属性を追加し、ブロックにRichTextコンポーネントを追加します。
{
"$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"
}
]
}
}
<RichText attribute="myRichText" />
ブロック内では RichText コンポーネントをいくつでも使用できます。
プロパティ
allowedFormats
allowedFormatsプロパティを使うと、RichText コンポーネントで使用できる書式を制限できます。
PHP
<RichText attribute="myRichText" allowedFormats="<?php echo esc_attr(wp_json_encode(['core/bold', 'core/italic'])); ?>" />
Twig
<RichText attribute="myRichText" allowedFormats="{{ ['core/bold', 'core/italic']|json_encode|escape('html_attr') }}" />
プレースホルダー
placeholderプロパティを使って、RichText コンポーネントのプレースホルダーを設定できます。
<RichText attribute="myRichText" placeholder="Enter some text" />
preserveWhiteSpace
値に含まれる空白文字を保持するかどうかを指定します。通常、タブ、改行、スペースは1つのスペースにまとめられます。有効にすると、ソフト改行は改行要素ではなく、改行文字として保存されます。
<RichText attribute="myRichText" preserveWhiteSpace="true" />
タグ
既定では、RichTextコンテンツはp要素内にレンダリングされます。tagプロパティを使って変更できます。
<RichText attribute="myRichText" tag="h1" />
withoutInteractiveFormatting
既定では、すべての書式設定コントロールが表示されます。この設定を使うと、コンテンツをインタラクティブにする書式設定コントロールを削除できます。
<RichText attribute="myRichText" withoutInteractiveFormatting="true" />
リピーターフィールド
RichText はリピーターフィールド内で使用できます。ブラケット記法とループインデックスを使って、対象の行を指定します。
{
"blockstudio": {
"attributes": [
{
"id": "items",
"type": "repeater",
"attributes": [
{
"id": "heading",
"type": "richtext"
}
]
}
]
}
}
<?php foreach ($a['items'] as $index => $item) : ?>
<RichText tag="h2" attribute="items[<?php echo $index; ?>].heading" placeholder="Enter heading" />
<?php endforeach; ?>
{% for item in a.items %}
<RichText tag="h2" attribute="items[{{ loop.index0 }}].heading" placeholder="Enter heading" />
{% endfor %}
attributeの値はrepeaterId[index].fieldIdのパターンに従います。indexはループ内の0始まりの行番号です。