Blockstudio
BlocksTemplating

Blade

Blade is a templating engine used primarily with the Laravel framework. It enables developers to create expressive, clean templates using a syntax that extends PHP in a simple and intuitive way. Blade templates facilitate common tasks like data display and layout management, helping streamline the development of dynamic web pages.

Setup

To use Blade templates with Blockstudio, you first need to install the jenssegers/blade package using Composer.

Terminal
composer require jenssegers/blade

Next, you need to add a filter to your theme's functions.php file to tell Blockstudio how to render Blade templates. Blockstudio automatically collects all Blade templates and maps their paths, allowing you to use Blade's dot syntax for includes and layouts.

functions.php
add_filter(
    "blockstudio/blocks/render",
    function ($value, $block) {
        $blockPath = $block->path;
        if (str_ends_with($blockPath, ".blade.php")) {
            // Ensure the Blade class exists before trying to use it.
            if (!class_exists('Jenssegers\Blade\Blade')) {
                // Optionally, you could log an error or return a message.
                return 'Error: Blade class not found. Please run "composer require jenssegers/blade".';
            }
            $data = $block->blockstudio["data"];
            $bladeData = $data["blade"];
            $blade = new \Jenssegers\Blade\Blade($bladeData["path"], sys_get_temp_dir());

            return $blade->render($bladeData["templates"][$block->name], [
                "a" => $data["attributes"],
                "attributes" => $data["attributes"],
                "b" => $data["block"],
                "block" => $data["block"],
                "c" => $data["context"],
                "context" => $data["context"],
            ]);
        }

        return $value;
    },
    10,
    2
);

Template Variables

Your Blade templates will have access to the following variables:

VariableDescription
$aAn alias for $attributes
$attributesThe block's attributes
$bAn alias for $block
$blockData related to the block itself
$cAn alias for $context
$contextThe block's context (e.g., post ID, post type when in a loop)

Usage

To use Blade for your block's template, create an index.blade.php file in your block's directory. Blockstudio will then automatically use this file for rendering the block.

index.blade.php
<div class="my-block">
  @if($a['title'])
    <h2>{{ $a['title'] }}</h2>
  @endif

  @if($a['content'])
    <p>{{ $a['content'] }}</p>
  @endif
</div>

On this page