
# Kontext

Wenn Blöcke innerhalb eines Loops verwendet werden (zum Beispiel in einem Query-Block), wird der Block für jede Iteration des Loops einmal ausgeführt. Blockstudio bietet praktische Kurzformen für den Zugriff auf den aktuellen Loop und den äußeren Kontext.


## 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>
```

## Verfügbare Variablen

In deinen Block-Templates kannst du auf folgende Variablen zugreifen:

| Variable | Kurzform | Beschreibung |
|----------|-----------|-------------|
| `$attributes` | `$a` | Blockattribute |
| `$block` | `$b` | Blockdaten (Name, Titel, postId, postType, Kontext usw.) |
| `$context` | `$c` | Kontext des übergeordneten Blocks |
| `$innerBlocks` | - | Inhalt der InnerBlocks |

## Blockdaten

Die Variable `$block` / `$b` enthält:

| Eigenschaft | Beschreibung |
|----------|-------------|
| `name` | Blockname (e.g, `my-theme/my-block`) |
| `title` | Blocktitel |
| `dir` | Pfad zum Blockverzeichnis |
| `url` | URL des Blockverzeichnisses |
| `postId` | ID des aktuellen Beitrags |
| `postType` | Typ des aktuellen Beitrags |
| `context` | Loop-Kontext (innerhalb eines Query-Blocks) |

Innerhalb eines Query-Blocks bleibt `postId` der gerade angezeigte Beitrag, während `$post_id` und `context.postId` dem aktuellen Loop-Element folgen. Gibt es keinen abgefragten Beitrag, etwa bei einer REST-Anfrage oder einem WP-CLI, ist `postId` der Beitrag, für den der Block gerendert wird. Er stammt aus dem `postId`-Blockkontext oder dem globalen Beitrag.

## Übergeordneter Kontext

Bei Verwendung von `usesContext` greifst du über `$context` auf die Daten des übergeordneten Blocks zu:

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

Blockstudio übernimmt `providesContext` automatisch. Du musst `usesContext` nur zum untergeordneten Block hinzufügen. Du brauchst `providesContext` nicht manuell in block.json des übergeordneten Blocks zu deklarieren, da Blockstudio es für alle Attribute registriert.

Weitere Informationen findest du unter [InnerBlocks-Kontext](https://blockstudio.dev/de/docs/blocks/react-components/innerblocks/#context).


> **[Blockkontext und Kommunikation](https://blockstudio.dev/de/guides/block-context/)**
>
> Praktische Muster: Kartenraster, Preistabellen und Abschnittscontainer, in denen Blöcke Daten gemeinsam nutzen müssen.
