跳转到正文

覆盖

Blockstudio 支持以非常精细的粒度覆盖区块。对于共享区块库,如果你想更改某个区块的行为,而无需从头创建新区块,这会很有用。

block.json

首先,将要覆盖的区块名称设为 name 键,并将 override 键设为 true。

JSON
{
  "name": "blockstudio/my-block",
  "title": "My overridden block title",
  "blockstudio": {
    "override": true
  }
}

将 override 属性设为 true 后,新 block.json 中的数据会与原区块的数据合并。这意味着你可以覆盖原区块的任何属性。

属性

可以通过 id 覆盖属性,也可以额外添加属性。例如,假设我们要覆盖区块的 width 属性,并添加一个新的 height 属性。

JSON
{
  "name": "blockstudio/my-block",
  "title": "My overridden block title",
  "blockstudio": {
    "override": true,
    "attributes": [
      {
        "id": "width",
        "type": "number",
        "default": 280,
        "label": "Override width"
      },
      {
        "id": "height",
        "type": "number",
        "default": 280,
        "label": "New height"
      }
    ]
  }
}

如果找到具有相同 id 的属性,其数据就会与原属性合并。未找到的属性会添加到区块中。

警告

覆盖属性时,必须提供原属性的 type,即使它保持不变也一样。

复杂结构

覆盖具有复杂结构(重复器、组、标签页等)的属性时,必须提供该属性的完整结构,直到需要覆盖的项目为止。

JSON
{
  "name": "blockstudio/my-block",
  "blockstudio": {
    "override": true,
    "attributes": [
      {
        "id": "tabs",
        "type": "tabs",
        "tabs": [
          {
            "id": "tab1",
            "attributes": [
              {
                "key": "group1",
                "type": "group",
                "title": "Group",
                "attributes": [
                  {
                    "id": "text",
                    "type": "text",
                    "label": "Override text"
                  }
                ]
              }
            ]
          },
          {
            "id": "tab2",
            "title": "Override tab",
            "attributes": [
              {
                "id": "group",
                "type": "group",
                "title": "Group ID",
                "attributes": [
                  {
                    "id": "text",
                    "type": "text",
                    "label": "Override text"
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
}

资源

如果文件名匹配,资源文件就会被替换。例如,如果原区块中有 style.css 文件,它会被覆盖区块中的 style.css 文件替换。名称与原区块文件不匹配的文件会添加到区块中。

渲染模板

可以通过提供新的模板文件来覆盖渲染模板,即 index.php、index.twig 或 index.blade.php。

Twig 区块

可以在 Twig 中使用 区块功能,以更精细的粒度覆盖 Twig 模板。

假设有以下用于虚构图像区块的渲染模板:

Twig
<h1>Images:</h1>
{% for image in a.images %}
  <div class="content">
    {% block image %}
      <img src="{{ image.url }}" class="image" />
    {% endblock %}
  </div>
{% endfor %}

无需替换整个模板,我们可以使用 Twig 的 extends 功能,在保留其余部分的同时覆盖模板中的特定部分。

Twig
{% extends 'index.twig' %}

{% block image %}
  <figure>
    <img src="{{ image.url }}" class="image" />
    <figcaption>{{ image.caption }}</figcaption>
  </figure>
{% endblock %}