How to Render ACF Custom Blocks with Laravel Blade in Roots Sage WordPress Theme?

441 views Asked by At

I'm currently integrating custom ACF Gutenberg blocks into a WordPress project that uses the Roots Sage theme. The challenge I'm facing is in rendering the blocks using Laravel Blade instead of plain PHP, specifically with the renderCallback option that ACF provides.

My current setup is:

  • All blocks are located in the resources/views/blocks directory.
  • Inside each block folder, I have a block.json file for block metadata and a render.php file for the block's output using plain PHP.

Here's the block registration code:

add_action('acf/init', function () {
    $blocks_dir = get_template_directory() . '/resources/views/blocks';

    if (is_dir($blocks_dir)) {
        foreach (new DirectoryIterator($blocks_dir) as $fileInfo) {
            if ($fileInfo->isDir() && !$fileInfo->isDot()) {
                register_block_type($fileInfo->getPathname());
            }
        }
    }
});

Using the above approach with plain PHP templates works as expected. However, I'd like to utilize Laravel Blade for the block templates, given its cleaner syntax and benefits.

Has anyone been able to set up Laravel Blade templates for ACF blocks within the Roots Sage theme? Any guidance on how to achieve this would be greatly appreciated.

1

There are 1 answers

0
Marcel Busch On

Here someone posted a solution: https://discourse.roots.io/t/register-an-acf-block-with-modern-practices/25887/5

Essentially, you have to add

 "acf": {
    "renderCallback": "\\App\\blade_render_callback",
    "blockVersion": 2
  }

to your block.json and then define a render callback like so

/**
 * Callback for rendering Blade templates.
 * Name of the Blade template at resources/views/blocks/{title}.blade.php
 */
function blade_render_callback($block, string $content = '', bool $is_preview = false, int $post_id = 0)
{
    // THEME_BLOCK_SLUG should be your theme name i think?
    $slug                = str_replace(THEME_BLOCK_SLUG . '/', '', $block['name']);
    $block['slug']       = $slug;

        echo \Roots\view('blocks.' . $block['slug'] . '.' . $block['slug'], [ 'block' => $block ])->render();
}