古腾堡渲染 locate_template

问题描述

我想用带有 create-guten-block 的古腾堡服务器端渲染一个简单的模板。

init.PHP:

function melaniemueller_templateparts_block_cgb_block_assets() {  

register_block_type(
        'cgb/block-melaniemueller-templateparts-block',array(
            
            'render_callback' => 'mmu_block_render',)
    );
    }
}

// Hook: Block assets.
add_action( 'init','melaniemueller_templateparts_block_cgb_block_assets' );
    
function mmu_block_render($attr,$content) {
       locate_template( 'custom\PHP\templates\header\header_main_1.PHP',true );
    }

block.js:

registerBlockType( 'cgb/block-melaniemueller-templateparts-block',{
    // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
    title: __( 'melaniemueller-templateparts-block - CGB Block' ),// Block title.
    icon: 'shield',// Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
    category: 'common',// Block category — Group blocks together based on common traits E.g. common,formatting,layout widgets,embed.
    keywords: [
        __( 'melaniemueller-templateparts-block — CGB Block' ),__( 'CGB Example' ),__( 'create-guten-block' ),],edit: function( { attributes } ) {
        return (
            <ServerSideRender
                block="cgb/block-melaniemueller-templateparts-block"
                attributes={ attributes }
            />
        );
    },save: function( { } ) {
        return null;
    },} );

但是如果我想渲染这部分,我会在 Chrome 的 Quirks-Mode 的 edit 函数中发现一个错误

Error loading block: The response is not a valid JSON response.

有人知道我做错了什么吗?

解决方法

您的块注册设置很好。问题是您的函数 mmu_block_render() 没有为要呈现的 <ServerSideRender> 返回有效值。

<ServerSideRender> 用于在块编辑器中呈现动态内容的预览。它不打算像您的函数尝试那样加载完整的模板文件。因此,locate_template 不会返回有效值。

以下是两个示例,第一个重现了所看到的错误,第二个显示了相同的函数已更正以呈现有效结果。我选择了函数 the_title(),因为它在头模板文件中最常见:

无效

<?php
function mmu_block_render($attr,$content){
    // the_title echo is set to "true",printing the value 
    return "<header>". the_title('<h1>','</h1>',true)."</header>";
}
?>

有效 返回 the_title 的值,回调函数按预期呈现,例如:

<?php
function mmu_block_render($attr,$content){
    // // the_title echo is set to "false",returning the value 
    return "<header>". the_title('<h1>',false)."</header>";
}
?>

如果您替换您的函数并运行上面的两个示例,您将能够处理模板文件的关键部分并确保它们返回一个值并正确呈现。