使用 InnerBlocks 模板的 WordPress 块转换

WordPress block transforms with InnerBlocks template

我的插件有一个自定义块,它 包含 一个内部块模板,在 edit() 中这样定义...

const HEADING = [
    [
        "core/heading",
        {
            level: 2,
            placeholder: __("Enter a title", "myplugin"),
        },
    ],
];

...以后...

<div className="title">
    <InnerBlocks template={HEADING} templateLock="all" />
</div>

我想允许将现有的 core/heading 块转换为 myplugin/my-heading 块,所以我在 registerBlockType 中有以下代码开始...

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ({ content }) => {
                console.log(content);
                return wp.blocks.createBlock("myplugin/my-heading");
            },
        },
    ],
}

只要用 myplugin/my-heading 块替换 core/heading 就可以了。

问题是我不知道如何获取 content 并将其插入 innerblock 模板。

createBlock documentation 非常基础,我找不到任何示例说明当内容未映射到任何现有属性时这可能如何工作。

更新:这是完整的解决方案。我需要创建一个与我的模板匹配的块并将其作为数组传递给 innerblocks 参数:

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ({ content }) => {
                const innerBlocks = wp.blocks.createBlock("core/heading", {
                    content: content,
                    placeholder: __("Enter a title", "myplugin"),
                    level: 2,
                });
                return wp.blocks.createBlock("myplugin/my-heading", {}, [
                    innerBlocks,
                ]);
            },
        },
    ],
},

Block Transforms 上 WordPress 文档中的示例展示了如何将 content 作为第二个参数传递给 createBlock():

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ({ content }) => {
                console.log(content);
                return wp.blocks.createBlock("myplugin/my-heading", {
                    content, // content is inserted here
                });
            },
        },
    ],
}

带有内部块的块示例:

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ( attributes, innerBlocks ) => {
                return wp.blocks.createBlock(
                    'myplugin/my-heading',
                    attributes,
                    innerBlocks
                );
            },
        },
    ],
}