【问题标题】:Gutenberg render locate_template古腾堡渲染 locate_template
【发布时间】:2021-08-24 12:04:46
【问题描述】:

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

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-function 中遇到一个错误。

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

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

【问题讨论】:

  • 您需要分享您的代码(或至少是 Minimal, Reproducible Example),以便我们提供帮助。否则,我们只能根据您提供的信息进行猜测。
  • 对不起.....感谢您的更新。我更新了我的示例。
  • @Melanie 我想你忘了在渲染回调中返回一些东西 (mmu_block_render)。
  • 已经在locate_templatesource中返回了

标签: wordpress wordpress-gutenberg gutenberg-blocks wordpress-plugin-creation project-gutenberg


【解决方案1】:

您的块注册设置很好。问题是你的函数 mmu_block_render() 没有返回一个有效的值让 &lt;ServerSideRender&gt; 渲染。

&lt;ServerSideRender&gt; 用于在块编辑器中呈现动态内容的预览。它并不打算像您的函数尝试那样加载完整的模板文件。因此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 的值被返回,回调函数按预期呈现 eg:

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

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

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 2023-02-11
    • 2019-02-16
    • 2011-04-02
    • 2019-06-15
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多