
# InnerBlocks

内部区块允许你在区块中插入其他区块。在底层，Blockstudio 使用 [内部区块](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/nested-blocks-inner-blocks/) 组件。请注意，每个区块只能使用一个内部区块组件，这是 WordPress 限制。

## 基本用法

要使用 InnerBlocks，请将 `<InnerBlocks />` 组件添加到区块模板中：

```php title="index.php"
<InnerBlocks />
```

组合方式由你决定。你可以将 `InnerBlocks` 组件嵌套任意层级，也可以单独使用。

## 属性

### allowedBlocks

`allowedBlocks` 属性用于定义可以插入 `InnerBlocks` 组件中的区块。


#### PHP

```php title="index.php"
<InnerBlocks allowedBlocks="<?php echo esc_attr(wp_json_encode(['core/heading', 'core/paragraph'])); ?>" />
```

#### Twig

```twig title="index.twig"
<InnerBlocks allowedBlocks="{{ ['core/heading', 'core/paragraph']|json_encode|escape('html_attr') }}" />
```

`allowedBlocks` 也接受由服务器展开的令牌。这些令牌会在编辑器接收模板之前展开，而字面区块名称保持不变。

| 令牌 | 说明 |
|-------|-------------|
| `namespace/*` | 该命名空间中所有已注册的区块 |
| `category:<slug>` | 该 WordPress 区块类别中所有已注册的区块 |
| `@theme` | 从当前主题注册的所有 Blockstudio 区块 |

展开后的条目会按作者指定的顺序去重：

```php title="index.php"
<InnerBlocks allowedBlocks="<?php echo esc_attr(wp_json_encode([
  'core/paragraph',
  'category:content',
  'bsui/field',
])); ?>" />
```

解析后没有对应区块的令牌会被忽略。前端输出保持不变，因为 `allowedBlocks` 仅供编辑器使用。

### 标签

默认情况下，`InnerBlocks` 组件会渲染为 `div` 元素。你可以使用 `tag` 属性更改此设置。

```php title="index.php"
<InnerBlocks tag="section" />
```

### 模板

`template` 属性用于为 `InnerBlocks` 组件定义模板。


#### PHP

```php title="index.php"
<InnerBlocks template="<?php echo esc_attr(wp_json_encode([
  ['core/heading', ['placeholder' => 'Book Title']],
  ['core/paragraph', ['placeholder' => 'Summary']]
])); ?>" />
```

#### Twig

```twig title="index.twig"
<InnerBlocks template="{{ [
  ['core/heading', { placeholder: 'Book Title' }],
  ['core/paragraph', { placeholder: 'Summary' }]
]|json_encode|escape('html_attr') }}" />
```

### templateLock

`templateLock` 属性用于定义模板是否可以修改。

| 值 | 说明 |
|-------|-------------|
| `contentOnly` | 禁止所有操作。没有内容的区块类型会从列表视图中隐藏。子区块无法覆盖此设置。 |
| `all` | 禁止所有操作。无法插入、移动或删除区块。 |
| `insert` | 禁止插入或移除区块，但允许移动现有区块。 |
| `false` | 即使父区块包含锁定设置，也禁止应用锁定。 |

### renderAppender

`renderAppender` 属性用于定义区块添加器的类型。

| 值 | 描述 |
|-------|-------------|
| `default` | 显示默认区块追加器（允许段落区块时显示段落样式的追加器） |
| `button` | 显示带 + 图标的按钮作为追加器 |

### useBlockProps

`useBlockProps` 会移除编辑器中 `InnerBlocks` 组件的外层包装器。
有关详情，请参阅 [useBlockProps](https://blockstudio.dev/zh/docs/blocks/react-components/useblockprops/)。

## 上下文

### 注册

Blockstudio 支持 `InnerBlocks` 组件的上下文。这让你可以将数据从父区块传递给子区块。它底层使用了 WordPress核心[上下文机制](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-context/)，而 Blockstudio 提供了更便捷的 API。

你无需单独定义要传入上下文的所有属性，只需订阅父区块的所有属性即可。

每个子区块都会收到其父区块自己的值，包括编辑器首次预加载渲染时的值。更新提供者的字段后，其子区块会在编辑器中更新，即使上一次渲染仍在加载。不同提供者下相同的子区块会保留各自独立的上下文缓存渲染结果。

假设你设置了如下容器区块：

```json title="container/block.json"
{
  "$schema": "https://blockstudio.dev/schema/block",
  "name": "blockstudio/container",
  "title": "Container",
  "category": "design",
  "icon": "star-filled",
  "description": "Container block.",
  "blockstudio": {
    "attributes": [
      {
        "id": "full-width",
        "type": "toggle",
        "label": "Makes section full width"
      }
    ]
  }
}
```

在子区块中，只需使用 `usesContext` 属性并指定父区块名称，即可在区块模板中访问父区块的所有属性。

```json title="element/block.json"
{
  "$schema": "https://blockstudio.dev/schema/block",
  "name": "blockstudio/element",
  "title": "Element",
  "category": "design",
  "icon": "star-filled",
  "description": "Element block.",
  "usesContext": ["blockstudio/container"],
  "parent": ["blockstudio/container"],
  "blockstudio": true
}
```

### 模板

在区块模板中，可以使用 `$context` 和 `$c` 变量访问所有父区块属性。父区块数据发生变化时，子区块会在编辑器中自动重新加载。


#### PHP

```php title="index.php"
<?php $container = $context['blockstudio/container']; ?>

<h1>
  <?php echo $container['full-width']
      ? 'is full width'
      : 'no full width'; ?>
</h1>
```

#### Twig

```twig title="index.twig"
{% set container = context['blockstudio/container'] %}

<h1>
  {{ container['full-width']
      ? 'is full width'
      : 'no full width' }}
</h1>
```

## 前端包装器

`InnerBlocks` 必须在编辑器中为其子元素渲染一个包装元素，但你可以使用 `blockstudio/blocks/components/inner_blocks/frontend/wrap` 过滤器将其从前端移除。

```php title="functions.php"
add_filter('blockstudio/blocks/components/inner_blocks/frontend/wrap', function($wrap, $block) {
  return false; // Remove wrapper
}, 10, 2);
```

## 提前返回

如果你想从区块的 `render` 方法中提前返回，可以检查 `$innerBlocks` 变量是否为空。如果没有内部区块时你不想渲染任何内容，这会很有用。

```php title="index.php"
<?php if (strip_tags($innerBlocks) === '') {
  return;
} ?>
<InnerBlocks tag="section" />
```

由于 `<InnerBlocks/>` 始终会渲染一个空段落标签，你可以使用 `strip_tags` 函数检查内容是否为空。

## 动态模板

[选择](https://blockstudio.dev/zh/docs/blocks/attributes/field-types/#select)和 [单选](https://blockstudio.dev/zh/docs/blocks/attributes/field-types/#radio)字段类型支持根据字段值动态生成 `InnerBlocks` 模板。如果你想让用户为 `InnerBlocks` 组件选择不同模板，这项功能会很有用。

只需在选项数组中添加一个 `innerBlocks` 键并指定模板即可：

```json title="block.json"
{
  "$schema": "https://blockstudio.dev/schema/block",
  "name": "blockstudio/dynamic-layout",
  "title": "Dynamic Layout",
  "blockstudio": {
    "attributes": [
      {
        "id": "layout",
        "type": "select",
        "label": "Layout",
        "options": [
          {
            "value": "1",
            "label": "Two Columns",
            "innerBlocks": [
              {
                "name": "core/columns",
                "innerBlocks": [
                  {
                    "name": "core/column",
                    "innerBlocks": [
                      {
                        "name": "core/heading",
                        "attributes": {
                          "content": "Left Heading",
                          "level": 1
                        }
                      }
                    ]
                  },
                  {
                    "name": "core/column",
                    "innerBlocks": [
                      {
                        "name": "core/heading",
                        "attributes": {
                          "content": "Right Heading",
                          "level": 1
                        }
                      }
                    ]
                  }
                ]
              }
            ]
          },
          {
            "value": "2",
            "label": "Single Column",
            "innerBlocks": [
              {
                "name": "core/heading",
                "attributes": {
                  "content": "Main Heading",
                  "level": 1
                }
              },
              {
                "name": "core/paragraph",
                "attributes": {
                  "content": "Main content goes here."
                }
              }
            ]
          }
        ],
        "allowNull": "Select a layout"
      }
    ]
  }
}
```


> **[区块上下文与通信](https://blockstudio.dev/zh/guides/block-context/)**
>
> 了解父区块和子区块如何通过上下文共享数据。
