注册属性
属性定义在 block.json 文件的 blockstudio.attributes 数组中。
基本示例
JSON
{
"name": "my-theme/my-block",
"title": "My Block",
"blockstudio": {
"attributes": [
{
"id": "title",
"type": "text",
"label": "Title"
},
{
"id": "content",
"type": "textarea",
"label": "Content"
}
]
}
}
属性
所有属性都有以下属性:
| 属性 | 类型 | 说明 |
|---|---|---|
id |
string | 属性的唯一标识符 |
type |
string | 字段类型(text、textarea、select 等) |
label |
string | 在编辑器中显示的标签 |
default |
mixed | 属性的默认值 |
help |
string | 显示在标签旁作为工具提示的帮助文本 |
position |
string | 字段的显示位置:inspector(默认)或 toolbar |
conditions |
array | 用于显示或隐藏字段的条件逻辑 |
位置
默认情况下,所有字段都会显示在区块检查器(侧边栏)中。你可以使用 position 属性更改此设置:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "alignment",
"type": "select",
"label": "Alignment",
"position": "toolbar",
"options": [
{ "value": "left", "label": "Left" },
{ "value": "center", "label": "Center" },
{ "value": "right", "label": "Right" }
]
}
]
}
}
默认值
使用 default 属性设置默认值:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "title",
"type": "text",
"label": "Title",
"default": "Hello World"
},
{
"id": "showBorder",
"type": "toggle",
"label": "Show Border",
"default": true
}
]
}
}
帮助文本
添加帮助文本以引导用户:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "apiKey",
"type": "text",
"label": "API Key",
"help": "Enter your API key from the settings page"
}
]
}
}
访问属性
在模板中,可通过 $a 简写(或 $attributes)访问属性:
PHP
<h1><?php echo $a['title']; ?></h1>
<p><?php echo $a['content']; ?></p>
也可以在 Twig 中:
Twig
<h1>{{ a.title }}</h1>
<p>{{ a.content }}</p>