Konteks
Saat blok digunakan di dalam loop (misalnya, blok Query), blok dijalankan sekali untuk setiap iterasi loop. Blockstudio menyediakan pintasan praktis untuk mengakses loop saat ini dan konteks luarnya.
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>
Variabel yang Tersedia
Di dalam templat blok, Anda dapat mengakses variabel berikut:
| Variabel | Singkatan | Deskripsi |
|---|---|---|
$attributes |
$a |
Atribut blok |
$block |
$b |
Data blok (nama, judul, postId, postType, konteks, dll.) |
$context |
$c |
Konteks blok induk |
$innerBlocks |
– | Konten InnerBlocks |
Data Blok
Variabel $block / $b berisi:
| Properti | Deskripsi |
|---|---|
name |
Nama blok (e.g., my-theme/my-block) |
title |
Judul blok |
dir |
Jalur direktori blok |
url |
URL direktori blok |
postId |
ID pos saat ini |
postType |
Jenis pos saat ini |
context |
Konteks loop (saat berada di dalam blok Query) |
Di dalam blok Query, postId tetap merujuk ke postingan yang sedang dilihat, sedangkan $post_id dan context.postId mengikuti item loop saat ini. Jika tidak ada postingan yang dikueri, misalnya pada permintaan REST atau WP-CLI, postId adalah postingan tempat blok dirender, yang diambil dari konteks blok postId atau postingan global.
Konteks Induk
Saat menggunakan usesContext, akses data blok induk melalui $context:
<?php
$parent = $context['parent-block/name'];
echo $parent['someAttribute'];
?>
Blockstudio menangani providesContext secara otomatis. Anda hanya perlu menambahkan usesContext ke blok anak. Anda tidak perlu mendeklarasikan providesContext secara manual di block.json milik blok induk, karena Blockstudio mendaftarkannya untuk semua atribut.
Lihat Konteks InnerBlocks untuk detail lebih lanjut.
Pola praktis: kisi kartu, tabel harga, dan pembungkus bagian yang blok-bloknya perlu berbagi data.