Konteksts
Ja bloki tiek izmantoti cilpā (piemēram, Query blokā), bloks tiek izpildīts vienu reizi katrā cilpas iterācijā. Blockstudio nodrošina ērtus īsceļus, lai piekļūtu pašreizējās cilpas datiem un ārējam kontekstam.
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
<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>
Pieejamie mainīgie
Bloku veidnēs varat piekļūt šiem mainīgajiem:
| Mainīgais | Īsais pieraksts | Apraksts |
|---|---|---|
$attributes |
$a |
Bloka atribūti |
$block |
$b |
Bloka dati (nosaukums, virsraksts, postId, postType, konteksts u. c.) |
$context |
$c |
Vecākbloka konteksts |
$innerBlocks |
– | InnerBlocks saturs |
Bloka dati
Mainīgais $block / $b satur:
| Īpašība | Apraksts |
|---|---|
name |
Bloka nosaukums (e.g., my-theme/my-block) |
title |
Bloka virsraksts |
dir |
Bloka direktorijas ceļš |
url |
Bloka direktorija URL |
postId |
Pašreizējā ieraksta ID |
postType |
Pašreizējā ieraksta tips |
context |
Cilpas konteksts (ja atrodaties Query blokā) |
Vaicājuma blokā postId paliek apskatāmais ieraksts, bet $post_id un context.postId seko pašreizējam cilpas vienumam. Ja vaicājuma ieraksta nav, piemēram, REST pieprasījumā vai WP-CLI, postId ir ieraksts, kuram bloks tiek renderēts; tas tiek iegūts no bloka konteksta postId vai globālā ieraksta.
Vecākbloka konteksts
Ja izmantojat usesContext, piekļūstiet vecākbloka datiem, izmantojot $context:
<?php
$parent = $context['parent-block/name'];
echo $parent['someAttribute'];
?>
Blockstudio automātiski apstrādā providesContext. Bērnblokam jāpievieno tikai usesContext. Nav manuāli jādeklarē providesContext vecākbloka block.json, jo Blockstudio reģistrē to visiem atribūtiem.
Plašāku informāciju skatiet InnerBlocks konteksta sadaļā.
Praktiski piemēri: karšu režģi, cenu tabulas un sadaļu ietvari, kuros blokiem ir jāapmainās ar datiem.