如何在Roots Sage主题中用Laravel Blade渲染ACF自定义区块?
实现Roots Sage中ACF Gutenberg区块的Blade模板渲染
1. 调整区块文件结构
- 保留
resources/views/blocks下的区块目录及block.json元数据文件 - 将原
render.php替换为Blade模板文件,命名为template.blade.php
2. 修改区块注册逻辑,自定义renderCallback
通过指定render_callback,让区块调用Sage的Blade渲染能力,替换原自动加载render.php的逻辑:
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()) { $block_path = $fileInfo->getPathname(); // 注册区块并绑定自定义渲染回调 register_block_type($block_path, [ 'render_callback' => function ($attributes, $content, $block) use ($block_path) { // 获取ACF区块字段数据 $fields = get_fields($block['id']); // 生成Blade模板路径(相对resources/views目录) $blade_template = str_replace(get_template_directory() . '/resources/views/', '', $block_path) . '/template'; // 调用Sage视图渲染方法,传递变量到Blade模板 echo \Roots\view($blade_template, [ 'attributes' => $attributes, 'content' => $content, 'block' => $block, 'fields' => $fields ]); } ]); } } } });
3. 编写Blade模板示例
以resources/views/blocks/my-block/template.blade.php为例,直接使用Blade语法调用字段数据:
<div class="my-block @if($attributes['className']) {{ $attributes['className'] }} @endif"> <h2>{{ $fields['block_title'] }}</h2> <div class="block-content"> {!! $fields['block_content'] !!} </div> </div>
4. 可选:简化渲染回调逻辑
将渲染逻辑封装为独立函数,让注册代码更整洁:
function render_acf_block_with_blade($attributes, $content, $block) { // 拼接Blade模板路径 $blade_template = 'blocks/' . $block['name'] . '/template'; // 获取区块字段数据 $fields = get_fields($block['id']); // 渲染模板并输出 echo \Roots\view($blade_template, compact('attributes', 'content', 'block', 'fields')); } 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(), [ 'render_callback' => 'render_acf_block_with_blade' ]); } } } });
注意事项
- Sage的
view()方法默认从resources/views目录开始查找模板,确保路径拼接正确 - 区块字段数据通过
$fields变量传递,直接使用ACF配置的字段名即可调用 - 若需编辑器预览也使用Blade渲染,可在
block.json中配置editorScript自定义预览逻辑
内容的提问来源于stack exchange,提问作者Kris D. J.
相关产品推荐
相关产品推荐

