40q / block-handler

处理Roots/Radicle项目中的自定义Gutenberg块

v1.0.7 2024-03-22 17:49 UTC

This package is auto-updated.

Last update: 2024-09-22 18:46:17 UTC


README

处理Roots/Radicle项目中的自定义Gutenberg块

安装

  1. 使用Composer安装包
composer require 40q/block-handler
  1. config/app.php中找到providers数组,并将服务提供者类添加到末尾。
'providers' => [
    // Other Service Providers...

    BlockHandler\Providers\BlockHandlerServiceProvider::class,
],
  1. BlocksServiceProvider.php中使用此包
add_filter('render_block', function ($block_content, $block) {
    try {
        $factory = app(BlockHandler::class);
        $handlerClass = $factory->getHandler($block['blockName']);

        if ($handlerClass) {
            $handlerInstance = new $handlerClass();
            return $handlerInstance($block_content, $block);
        }
    } catch (\Exception $e) {
        error_log($e->getMessage());
    }

    return $block_content;
}, 10, 2);
  1. app目录内创建一个Blocks文件夹,并将你的处理程序放在里面。

块处理程序

此包将尝试将app\Blocks目录中的每个文件用作块处理程序。为了按预期工作,请确保所有类都遵循BlockHandler合约。

可以使用40q命令行工具生成带有其块处理程序的块

40q codegen block

示例

<?php

namespace App\Blocks;
use BlockHandler\Contracts\BlockHandler;

class Modal implements BlockHandler {
    public function __invoke($block_content, $block) {
        return view('blocks.modal', [
            'block' => $block,
            'blockContent' => $block_content,
            'buttonText' => $block['attrs']['buttonText'] ?? null,
            'heading' => $block['attrs']['heading'] ?? null,
        ]);
    }
}