
# 上下文

在循环中使用区块时（例如 Query 区块），每次循环迭代都会执行一次该区块。Blockstudio 提供了便捷方式，可访问当前循环和外层上下文。


## PHP

```php title="index.php"
<div>
  <h1>
    This is the data of current
    element inside the loop:
    <?php echo $block['context']['postId'] ?>
    <?php echo $block['context']['postType'] ?>
  </h1>
  <h1>
    This is the data the current post:
    <?php echo $block['postId'] ?>
    <?php echo $block['postType'] ?>
  </h1>
</div>
```

## Twig

```twig title="index.twig"
<div>
  <h1>
    This is the data of current
    element inside the loop:
    {{ block.context.postId }}
    {{ block.context.postType }}
  </h1>
  <h1>
    This is the data the current post:
    {{ block.postId }}
    {{ block.postType }}
  </h1>
</div>
```

## 可用变量

在区块模板中，你可以访问以下变量：

| 变量 | 简写 | 说明 |
|----------|-----------|-------------|
| `$attributes` | `$a` | 区块属性 |
| `$block` | `$b` | 区块数据（名称、标题、postId、postType、上下文等） |
| `$context` | `$c` | 父区块上下文 |
| `$innerBlocks` | - | InnerBlocks 内容 |

## 区块数据

`$block` / `$b` 变量包含：

| 属性 | 说明 |
|----------|-------------|
| `name` | 区块名称（e.g、`my-theme/my-block`） |
| `title` | 区块标题 |
| `dir` | 区块目录路径 |
| `url` | 区块目录 URL |
| `postId` | 当前文章 ID |
| `postType` | 当前文章类型 |
| `context` | 循环上下文（在 Query 区块内时） |

在 Query 区块内，`postId` 始终指当前正在查看的文章，而 `$post_id` 和 `context.postId` 则跟随当前循环项。若没有查询到文章，例如在 REST 请求或 WP-CLI 中，`postId` 就是区块所针对的文章，取自 `postId` 区块上下文或全局文章。

## 父级上下文

使用 `usesContext` 时，通过 `$context` 访问父区块数据：

```php title="index.php"
<?php
$parent = $context['parent-block/name'];
echo $parent['someAttribute'];
?>
```

Blockstudio 会自动处理 `providesContext`。你只需将 `usesContext` 添加到子区块即可。无需在父区块的 block.json 中手动声明 `providesContext`，因为 Blockstudio 会为所有属性注册它。

请参阅 [InnerBlocks 上下文](https://blockstudio.dev/zh/docs/blocks/react-components/innerblocks/#context)了解更多详情。


> **[区块上下文与通信](https://blockstudio.dev/zh/guides/block-context/)**
>
> 实用模式：卡片网格、定价表和区块包装器，让区块之间能够共享数据。
