跳转到正文

HTML 实用工具

有时你需要在 CSS 或 JS 文件中使用属性值。Blockstudio 提供了辅助函数,可将属性渲染为数据属性或 CSS 变量。

示例区块

假设有一个区块,其属性如下:

JSON
{
  "blockstudio": {
    "attributes": [
      {
        "id": "message",
        "type": "text",
        "label": "My message"
      },
      {
        "id": "color",
        "type": "color",
        "label": "My color"
      }
    ]
  }
}

数据属性

bs_render_attributes 函数会将属性渲染为数据属性:

PHP

PHP
<h1 <?php bs_render_attributes($a); ?>>
  <?php echo $a['message']; ?>
</h1>

Twig

Twig
<h1 {{ fn('bs_render_attributes', a) }}>
  {{ a.message }}
</h1>

输出:

HTML
<h1 data-message="Hello" data-color="#7C3AED">
  Hello
</h1>

筛选属性

传入第二个参数以指定要渲染的属性:

PHP

PHP
<h1 <?php bs_render_attributes($a, ['color']); ?>>
  <?php echo $a['message']; ?>
</h1>

Twig

Twig
<h1 {{ fn('bs_render_attributes', a, ['color']) }}>
  {{ a.message }}
</h1>

输出:

HTML
<h1 data-color="#7C3AED">
  Hello
</h1>

返回但不渲染

使用 bs_attributes 获取字符串,但不回显:

PHP
<?php $attrs = bs_attributes($a); ?>

CSS 变量

bs_render_variables 函数会将属性渲染为 CSS 变量:

PHP

PHP
<h1 style="<?php bs_render_variables($a); ?>">
  <?php echo $a['message']; ?>
</h1>

Twig

Twig
<h1 style="{{ fn('bs_render_variables', a) }}">
  {{ a.message }}
</h1>

输出:

HTML
<h1 style="--message: Hello; --color: #7C3AED;">
  Hello
</h1>

筛选变量

PHP
<h1 style="<?php bs_render_variables($a, ['color']); ?>">

输出:

HTML
<h1 style="--color: #7C3AED;">
  Hello
</h1>

返回但不渲染

使用 bs_variables 获取字符串,但不回显:

PHP
<?php $vars = bs_variables($a); ?>

字符串转换

两个函数都会将属性 ID 转换为 kebab-case:

输入 输出
myAttribute my-attribute
my_attribute my-attribute
backgroundColor background-color

在 CSS 中使用

CSS
.my-block h1 {
  color: var(--color);
}

在 JavaScript 中使用

JavaScript
const block = document.querySelector('.my-block h1');
const color = block.dataset.color;
const message = block.dataset.message;