Assets - Code field

Last modified:

Beside static styles and scripts as files, Blockstudio also supports dynamic asset blocks via the code field. Depending on your use case, these can be scoped to the block.

Basic usage

At the most basic level, you can manually render the code field content in your template.

index.php
index.twig

          <div useBlockProps>
    <h1>My block</h1>
  </div>
  <style><?php echo $attributes['css']; ?></style>
Copy

          <div useBlockProps>
    <h1>My block</h1>
  </div>
  <style>{{ attributes.css }}</style>
Copy

Scoped selector

To avoid conflicts with other blocks, you can use the %selector% variable inside the code field alongside useBlockProps in your rendering template.

Example

Let's imagine that we want to target the h1 tag from the example above in our code field.


            %selector% h1 {
      color: red;
    }

      
Copy

Now, Blockstudio will do three things:

  • create a unique id for that block instance
  • replace %selector% with the unique id
  • add the same selector to the element marked with useBlockProps

The final output will be something like this:


            <div data-assets="c9abe0d95c2b">
      <h1>My block</h1>
    </div>
    <style>
      [data-assets="c9abe0d95c2b"] h1 {
        color: red;
      }
    </style>
Copy

Automatic rendering

Always having to render the style tag manually can be cumbersome. To make this process easier, you can use the asset attribute inside the code field.

block.json

            {
      "blockstudio": {
        "attributes": [
          {
            "type": "code",
            "id": "code",
            "label": "Custom CSS",
            "language": "css",
            "asset": true
          }
        ]
      }
    }

      
Copy

This will automatically create style tags for code blocks marked as css and move them to the head of the document. For fields marked with javascript as the language, script tags will be created instead and placed at the bottom of the body.

In extensions

When using code fields inside of extensions, the asset attribute is not necessary. Blockstudio will automatically render the code field content as an asset if the language is css or javascript.

Example

core.json

            {
      "$schema": "https://app.blockstudio.dev/schema/extend",
      "name": "core/*",
      "blockstudio": {
        "extend": true,
        "attributes": [
          {
            "id": "customCss",
            "type": "code",
            "label": "Custom css",
            "language": "css"
          }
        ]
      }
    }

      
Copy

No additional configuration is needed. The above will show a code field for every core/* block in the sidebar and automatically render the content as an asset to the page.