跳转到正文

区块上下文与通信

大多数区块都是独立的。它们有自己的字段和模板,也不关心周围的内容。但有些组件天然具有层级关系:父区块控制列数和间距的卡片网格、父区块设置货币的定价表,以及告知子区块使用浅色还是深色主题的区段包装器。

WordPress提供了 区块上下文API。父区块会公开部分数据,子区块则订阅这些数据。父区块发生变化时,子区块会自动更新。Blockstudio大大简化了这一过程:你完全不必配置 providesContext。每个 Blockstudio区块都会自动将所有属性作为上下文提供。子区块只需在自己的 block.json 中添加一行代码即可订阅。

本指南将介绍四种使用上下文的真实组件模式,分别展示不同的通信需求。

Blockstudio中的上下文工作方式

在标准 WordPress中,你必须先在 providesContext 中显式地将每个父级属性映射到上下文键,再在子区块的 usesContext 中列出这些键。Blockstudio完全省去了第一步。

父区块: 无需配置。每个 Blockstudio区块都会自动以区块名称为键提供其所有属性。

子区块: 添加 usesContext,并填写父区块名称:

JSON
{
  "usesContext": ["my-theme/parent-block"]
}

子模板: 通过 $context(或简写 $c)访问父区块属性:

PHP
<?php $parent = $context['my-theme/parent-block']; ?>
<p>Parent says: <?php echo esc_html( $parent['message'] ); ?></p>

整个设置就这么简单。父区块中无需添加 providesContext,无需映射属性,也无需注册代码。子区块会收到父区块经过转换的所有属性,也就是说,媒体字段会解析为附件数据,选择字段会遵循 returnFormat,重复器也会完整展开。

两种上下文

Blockstudio在模板中提供两个上下文变量,用途各不相同:

变量 包含内容 用途
$context / $c 父区块属性(通过 usesContext) 组件间通信
$block['context'] / $b['context'] WordPress循环数据(postId、postType) 查询区块循环

第一种用于区块与父区块通信。第二种用于查询循环中的区块,以便知道当前正在渲染哪篇文章。本指南将聚焦第一种。

编辑器支持

上下文会在编辑器中响应变化。用户更改父区块的字段值时,所有订阅该父区块上下文的子区块都会自动使用新值重新渲染。无需手动刷新。

区段包装器

最常见的上下文模式:为子区块提供主题设置的包装器区块。父区块包含背景颜色、文字颜色和内边距字段。子区块读取这些值,让自身样式保持一致。

父区块:区段

JSON
{
  "name": "my-theme/section",
  "title": "Section",
  "category": "design",
  "icon": "align-wide",
  "description": "Section wrapper with theme settings.",
  "blockstudio": {
    "attributes": [
      {
        "id": "theme",
        "type": "select",
        "label": "Theme",
        "default": "light",
        "options": [
          { "value": "light", "label": "Light" },
          { "value": "dark", "label": "Dark" },
          { "value": "accent", "label": "Accent" }
        ]
      },
      {
        "id": "spacing",
        "type": "select",
        "label": "Spacing",
        "default": "md",
        "options": [
          { "value": "sm", "label": "Small" },
          { "value": "md", "label": "Medium" },
          { "value": "lg", "label": "Large" }
        ]
      }
    ]
  }
}
PHP
<?php
$theme_classes = array(
	'light'  => 'bg-white text-gray-900',
	'dark'   => 'bg-gray-900 text-white',
	'accent' => 'bg-indigo-600 text-white',
);
$spacing_classes = array(
	'sm' => 'py-8',
	'md' => 'py-16',
	'lg' => 'py-24',
);
$classes = ( $theme_classes[ $a['theme'] ] ?? '' ) . ' ' . ( $spacing_classes[ $a['spacing'] ] ?? '' );
?>
<div useBlockProps class="<?php echo esc_attr( $classes ); ?>">
  <InnerBlocks
    allowedBlocks='<?php echo esc_attr( wp_json_encode( array( 'my-theme/section-heading', 'my-theme/section-text', 'core/columns', 'core/group' ) ) ); ?>'
  />
</div>

子区块:区段标题

JSON
{
  "name": "my-theme/section-heading",
  "title": "Section Heading",
  "category": "design",
  "icon": "heading",
  "description": "Heading that adapts to section theme.",
  "usesContext": ["my-theme/section"],
  "parent": ["my-theme/section"],
  "blockstudio": {
    "attributes": [
      { "id": "text", "type": "text", "label": "Heading", "default": "Section Title" },
      {
        "id": "size",
        "type": "select",
        "label": "Size",
        "default": "lg",
        "options": [
          { "value": "sm", "label": "Small" },
          { "value": "lg", "label": "Large" },
          { "value": "xl", "label": "Extra Large" }
        ]
      }
    ]
  }
}
PHP
<?php
$section = $context['my-theme/section'] ?? array();
$theme   = $section['theme'] ?? 'light';

$color_class = match ( $theme ) {
	'light'  => 'text-gray-900',
	'dark'   => 'text-white',
	'accent' => 'text-white',
	default  => 'text-gray-900',
};

$size_class = match ( $a['size'] ) {
	'sm' => 'text-2xl',
	'lg' => 'text-4xl',
	'xl' => 'text-6xl',
	default => 'text-4xl',
};
?>
<h2 useBlockProps class="<?php echo esc_attr( "$color_class $size_class font-bold" ); ?>">
  <?php echo esc_html( $a['text'] ); ?>
</h2>

此示例说明: 标题没有自己的颜色字段,而是从上下文中读取区段的 theme 值并据此调整。用户在编辑器中将区段从“浅色”切换为“深色”时,标题文字颜色会立即更新。

子区块 block.json 中的 parent 属性会限制区块可插入的位置。只有用户位于 my-theme/section 区块中时,它才会显示在插入器中。此项为可选设置,但对于仅适用于特定父区块的子区块,建议启用。

子区块:区段文本

JSON
{
  "name": "my-theme/section-text",
  "title": "Section Text",
  "category": "design",
  "icon": "text",
  "description": "Body text that adapts to section theme.",
  "usesContext": ["my-theme/section"],
  "parent": ["my-theme/section"],
  "blockstudio": {
    "attributes": [
      { "id": "text", "type": "textarea", "label": "Text", "default": "Section body text." }
    ]
  }
}
PHP
<?php
$section = $context['my-theme/section'] ?? array();
$theme   = $section['theme'] ?? 'light';

$color_class = match ( $theme ) {
	'dark', 'accent' => 'text-white/80',
	default          => 'text-gray-600',
};
?>
<p useBlockProps class="<?php echo esc_attr( "$color_class text-lg leading-relaxed" ); ?>">
  <?php echo esc_html( $a['text'] ); ?>
</p>

现在,标题和文本都会响应区段主题。用户只需在父区块中选择一次主题,所有子区块都会随之调整。

卡片网格

网格父区块负责控制卡片子区块的布局设置。父区块定义列数和间距。子区块使用这些值来了解自身的布局上下文,并相应调整样式。

父区块:卡片网格

JSON
{
  "name": "my-theme/card-grid",
  "title": "Card Grid",
  "category": "design",
  "icon": "grid-view",
  "description": "Responsive card grid with configurable columns.",
  "blockstudio": {
    "attributes": [
      {
        "id": "columns",
        "type": "range",
        "label": "Columns",
        "default": 3,
        "min": 1,
        "max": 4,
        "step": 1
      },
      {
        "id": "gap",
        "type": "select",
        "label": "Gap",
        "default": "md",
        "options": [
          { "value": "sm", "label": "Small" },
          { "value": "md", "label": "Medium" },
          { "value": "lg", "label": "Large" }
        ]
      },
      {
        "id": "cardStyle",
        "type": "select",
        "label": "Card Style",
        "default": "elevated",
        "options": [
          { "value": "elevated", "label": "Elevated (shadow)" },
          { "value": "outlined", "label": "Outlined (border)" },
          { "value": "flat", "label": "Flat (no decoration)" }
        ]
      }
    ]
  }
}
PHP
<?php
$gap_class = match ( $a['gap'] ) {
	'sm' => 'gap-4',
	'md' => 'gap-6',
	'lg' => 'gap-8',
	default => 'gap-6',
};
?>
<div useBlockProps class="grid grid-cols-<?php echo esc_attr( $a['columns'] ); ?> <?php echo esc_attr( $gap_class ); ?>">
  <InnerBlocks
    allowedBlocks='<?php echo esc_attr( wp_json_encode( array( 'my-theme/card' ) ) ); ?>'
    template='<?php echo esc_attr( wp_json_encode( array(
      array( 'my-theme/card', array() ),
      array( 'my-theme/card', array() ),
      array( 'my-theme/card', array() ),
    ) ) ); ?>'
  />
</div>

子区块:卡片

JSON
{
  "name": "my-theme/card",
  "title": "Card",
  "category": "design",
  "icon": "cover-image",
  "description": "Card that inherits style from its grid parent.",
  "usesContext": ["my-theme/card-grid"],
  "parent": ["my-theme/card-grid"],
  "blockstudio": {
    "attributes": [
      { "id": "image", "type": "files", "label": "Image", "multiple": false },
      { "id": "title", "type": "text", "label": "Title", "default": "Card Title" },
      { "id": "description", "type": "textarea", "label": "Description", "default": "Card description goes here." },
      { "id": "url", "type": "link", "label": "Link" }
    ]
  }
}
PHP
<?php
$grid      = $context['my-theme/card-grid'] ?? array();
$card_style = $grid['cardStyle'] ?? 'elevated';

$style_class = match ( $card_style ) {
	'elevated' => 'bg-white rounded-xl shadow-md',
	'outlined' => 'bg-white rounded-xl border border-gray-200',
	'flat'     => 'bg-gray-50 rounded-xl',
	default    => 'bg-white rounded-xl shadow-md',
};
?>
<div useBlockProps class="<?php echo esc_attr( "$style_class overflow-hidden" ); ?>">
  <?php if ( $a['image'] ) : ?>
    <img
      src="<?php echo esc_url( $a['image']['url'] ); ?>"
      alt="<?php echo esc_attr( $a['image']['alt'] ); ?>"
      class="w-full aspect-video object-cover" />
  <?php endif; ?>
  <div class="p-6">
    <h3 class="text-lg font-semibold"><?php echo esc_html( $a['title'] ); ?></h3>
    <p class="mt-2 text-gray-600"><?php echo esc_html( $a['description'] ); ?></p>
    <?php if ( $a['url'] ) : ?>
      <a href="<?php echo esc_url( $a['url']['url'] ); ?>" class="mt-4 inline-block text-indigo-600 font-medium">
        <?php echo esc_html( $a['url']['title'] ?: 'Learn more' ); ?>
      </a>
    <?php endif; ?>
  </div>
</div>

此示例说明: 卡片没有自己的样式字段,而是从网格父区块读取 cardStyle。用户将网格从“凸起”切换为“描边”时,网格中的所有卡片会同时更新。这样既能保持卡片的视觉一致性,也不必让用户逐个更新。

<InnerBlocks> 上的 template 属性会预先在网格中放入三张卡片,为用户提供起始内容。

定价表

这是一种更高级的模式:父区块提供共享的业务逻辑(货币、计费周期),子区块则在显示内容时使用这些信息。这样就不必在每个定价档位中重复相同的字段。

父区块:定价表

JSON
{
  "name": "my-theme/pricing-table",
  "title": "Pricing Table",
  "category": "text",
  "icon": "money-alt",
  "description": "Pricing comparison with shared currency and billing settings.",
  "blockstudio": {
    "attributes": [
      {
        "id": "currency",
        "type": "select",
        "label": "Currency",
        "default": "usd",
        "options": [
          { "value": "usd", "label": "USD ($)" },
          { "value": "eur", "label": "EUR (\u20ac)" },
          { "value": "gbp", "label": "GBP (\u00a3)" }
        ]
      },
      {
        "id": "period",
        "type": "select",
        "label": "Billing Period",
        "default": "month",
        "options": [
          { "value": "month", "label": "Monthly" },
          { "value": "year", "label": "Yearly" }
        ]
      }
    ]
  }
}
PHP
<div useBlockProps class="grid grid-cols-3 gap-6 items-start">
  <InnerBlocks
    allowedBlocks='<?php echo esc_attr( wp_json_encode( array( 'my-theme/pricing-tier' ) ) ); ?>'
    template='<?php echo esc_attr( wp_json_encode( array(
      array( 'my-theme/pricing-tier', array( 'name' => 'Starter', 'price' => 9 ) ),
      array( 'my-theme/pricing-tier', array( 'name' => 'Pro', 'price' => 29, 'highlighted' => true ) ),
      array( 'my-theme/pricing-tier', array( 'name' => 'Enterprise', 'price' => 99 ) ),
    ) ) ); ?>'
  />
</div>

子区块:定价档位

JSON
{
  "name": "my-theme/pricing-tier",
  "title": "Pricing Tier",
  "category": "text",
  "icon": "tag",
  "description": "Single pricing tier that reads currency from parent.",
  "usesContext": ["my-theme/pricing-table"],
  "parent": ["my-theme/pricing-table"],
  "blockstudio": {
    "attributes": [
      { "id": "name", "type": "text", "label": "Tier Name", "default": "Plan" },
      { "id": "price", "type": "number", "label": "Price", "default": 0 },
      { "id": "highlighted", "type": "toggle", "label": "Highlighted", "default": false },
      {
        "id": "features",
        "type": "repeater",
        "label": "Features",
        "attributes": [
          { "id": "text", "type": "text", "label": "Feature" }
        ]
      }
    ]
  }
}
PHP
<?php
$table    = $context['my-theme/pricing-table'] ?? array();
$currency = $table['currency'] ?? 'usd';
$period   = $table['period'] ?? 'month';

$symbols = array(
	'usd' => '$',
	'eur' => "\u{20AC}",
	'gbp' => "\u{00A3}",
);
$symbol = $symbols[ $currency ] ?? '$';

$period_label = $period === 'year' ? '/year' : '/month';

$border_class = $a['highlighted'] ? 'border-2 border-indigo-600' : 'border border-gray-200';
?>
<div useBlockProps class="<?php echo esc_attr( "rounded-xl p-8 $border_class" ); ?>">
  <h3 class="text-lg font-semibold"><?php echo esc_html( $a['name'] ); ?></h3>
  <div class="mt-4">
    <span class="text-4xl font-bold"><?php echo esc_html( $symbol . $a['price'] ); ?></span>
    <span class="text-gray-500"><?php echo esc_html( $period_label ); ?></span>
  </div>
  <?php if ( ! empty( $a['features'] ) ) : ?>
    <ul class="mt-6 space-y-3">
      <?php foreach ( $a['features'] as $feature ) : ?>
        <li class="flex items-center gap-2">
          <span class="text-indigo-600">&#10003;</span>
          <?php echo esc_html( $feature['text'] ); ?>
        </li>
      <?php endforeach; ?>
    </ul>
  <?php endif; ?>
</div>

此示例说明: 货币符号和计费周期只需在定价表中定义一次,就会由所有档位继承。用户从 USD 切换到 EUR 时,三个档位的货币符号会同时更新。如果没有上下文,你就得在每个档位中重复设置货币字段,并手动保持同步。

查询循环上下文

WordPress还会在查询区块循环中提供另一种上下文。在循环内部渲染区块时,$block['context'](或 $b['context'])包含当前迭代的文章数据:

PHP
<?php
$loop_post_id   = $block['context']['postId'];
$loop_post_type = $block['context']['postType'];
?>
<article useBlockProps>
  <h2><?php echo esc_html( get_the_title( $loop_post_id ) ); ?></h2>
  <p><?php echo esc_html( get_the_excerpt( $loop_post_id ) ); ?></p>
  <a href="<?php echo esc_url( get_permalink( $loop_post_id ) ); ?>">Read more</a>
</article>

这与父区块上下文($context / $c)不同。循环上下文由 WordPress 核心提供,且只包含 postId 和 postType。为此,你无需在 block.json 中使用 usesContext。Blockstudio会自动让每个区块订阅 postId 和 postType。

循环上下文的适用场景: 查询区块中的自定义文章卡片、显示文章元数据的区块,或任何需要针对循环中每篇文章进行不同渲染的区块。

无论是否处于循环上下文,你也可以访问外层页面的文章数据:

PHP
$outer_post_id   = $block['postId'];   // always the current page
$loop_post_id    = $block['context']['postId'];  // current loop iteration

嵌套上下文

上下文会沿整个区块树传递,而不只是在相邻层级之间。如果区块 A 包含区块 B,而区块 B 又包含区块 C,那么 C 可以订阅 A 的上下文。这是因为 WordPress会通过 InnerBlocks 将上下文传递到每一层。

代码
my-theme/section (theme: "dark")
└── core/columns
    └── core/column
        └── my-theme/section-heading (reads section context)

标题不必是区段的直接子区块。它可以嵌套在核心区块(列、组等)中,仍然接收区段上下文。usesContext订阅在任意嵌套深度都有效。

多个父区块

子区块可以订阅多个父区块:

JSON
{
  "usesContext": ["my-theme/section", "my-theme/card-grid"]
}
PHP
<?php
$section = $context['my-theme/section'] ?? array();
$grid    = $context['my-theme/card-grid'] ?? array();

$theme     = $section['theme'] ?? 'light';
$cardStyle = $grid['cardStyle'] ?? 'elevated';
?>

如果祖先树中找不到某个父区块,其键就不会出现在 $context中。读取上下文值时,始终使用空值合并运算符(??)或检查 isset(),以防区块在预期的父区块之外使用。

防御性编码

使用上下文的区块应始终处理父区块缺失的情况。用户可能会在预期父区块之外插入该区块,或者父区块可能没有为某个字段设置值。

PHP
<?php
// Always provide defaults
$section = $context['my-theme/section'] ?? array();
$theme   = $section['theme'] ?? 'light';
$spacing = $section['spacing'] ?? 'md';
?>

如果要确保子区块只能出现在其父区块内部,请添加 parent 属性:

JSON
{
  "parent": ["my-theme/section"]
}

用户不在 my-theme/section 区块内时,这会将子区块从插入器中移除。如果没有 parent,子区块会显示在任何位置,你的模板就需要妥善处理上下文缺失的情况。

对于脱离容器就没有意义的区块(如定价档位、卡片网格项),请使用 parent。对于可独立使用、但能从父区块获得额外样式的区块(如也可单独使用的区段标题),则无需使用。

提示

上下文为只读。 子区块无法通过上下文修改父区块的属性。数据只会向下传递,不会向上传递。如果子区块需要向父区块传递信息,就需要采用其他方法(例如通过交互性 API 共享服务器状态,或使用文章元数据)。

会提供所有属性。 Blockstudio会提供父区块的每个属性,而不仅是你选择的属性。因此,子区块可以访问父区块定义的任何字段。即使父区块之后添加了新字段,子区块也能自动访问,无需更改配置。

转换后的值。 上下文值会经过 Blockstudio的属性转换流程。文件字段包含完整的附件数据(url、alt、width、height),选择字段遵循 returnFormat,重复器则会递归展开。你获得的数据结构与父模板中的 $a 相同。

编辑器响应性。 用户在编辑器中更改父区块字段时,子区块会自动重新渲染。这使用了 WordPress内置的上下文传递功能,以及一个 React useEffect,用于检测上下文变化并触发子区块的服务器端重新渲染。

保持上下文精简。 虽然 Blockstudio会自动提供父区块的所有属性,但子区块只应读取实际需要的值。这不是性能问题(数据已经存在),而是代码清晰度问题。请记录子区块依赖的父区块字段,让后续开发者了解它们之间的关系。

后续步骤

  • 上下文参考:模板变量、循环上下文和 $block 数据结构。
  • InnerBlocks:<InnerBlocks />组件、allowedBlocks、模板和前端包装器筛选器。
  • 交互性指南:适用于区块间的客户端响应性(交互性 API处理上下文无法实现的功能:从子区块到父区块的通信、跨区块状态,以及由用户触发的更新)。