Lewati ke konten

Utilitas HTML

Terkadang Anda perlu menggunakan nilai atribut dalam file CSS atau JS. Blockstudio menyediakan fungsi helper untuk merender atribut sebagai atribut data atau variabel CSS.

Contoh Blok

Bayangkan sebuah blok dengan atribut berikut:

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

Atribut Data

Fungsi bs_render_attributes merender atribut sebagai atribut data:

PHP

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

Twig

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

Output:

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

Memfilter Atribut

Teruskan parameter kedua untuk menentukan atribut yang akan dirender:

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>

Output:

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

Mengembalikan Tanpa Merender

Gunakan bs_attributes untuk mendapatkan string tanpa mencetaknya:

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

Variabel CSS

Fungsi bs_render_variables merender atribut sebagai variabel 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>

Output:

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

Memfilter Variabel

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

Output:

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

Mengembalikan Tanpa Merender

Gunakan bs_variables untuk mendapatkan string tanpa mencetaknya:

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

Konversi String

Kedua fungsi mengonversi ID atribut menjadi kebab-case:

Input Output
myAttribute my-attribute
my_attribute my-attribute
backgroundColor background-color

Menggunakan di CSS

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

Menggunakan di JavaScript

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