You need to enable JavaScript to run this app. Gutenberg自定义代码片段块渲染异常:pre标签冗余、代码换行丢失及存储格式问题
优惠活动
大模型
产品
解决方案
定价
更多

Gutenberg自定义代码片段块渲染异常:pre标签冗余、代码换行丢失及存储格式问题

自定义Gutenberg代码块异常修复步骤

1. 编辑器端组件逻辑修正

  • 替换默认RichText的格式化逻辑,从根源上避免换行被转成<br>标签:
    • 块属性注册时,将内容提取规则设为纯文本模式,不解析内部HTML:
    attributes: {
        code_content: {
            type: 'string',
            source: 'text',
            selector: 'pre > code'
        }
    }
    
    • 编辑态的RichText组件开启纯文本模式,关闭所有自动格式化能力:
    <RichText
        tagName="code"
        value={ attributes.code_content }
        onChange={ (val) => setAttributes( { code_content: val } ) }
        plainText // 强制纯文本输入,不做HTML转义
        multiline={ false } // 禁止把多换行解析为独立块标签
        withoutInteractiveFormatting // 屏蔽所有内置格式化按钮的修改
    />
    

2. 保存端输出规范

  • 严格输出无冗余属性的标签结构,不要给pre、code标签主动拼接任何class、样式属性:
save: ({ attributes }) => {
    return (
        <pre>
            <code>{ attributes.code_content }</code>
        </pre>
    );
}
  • 不要引入核心pre块的默认样式类,避免自定义块和系统代码块的类名串扰。

3. 存储环节过滤修正

  • 绕过WordPress全局wpautop对pre标签内部内容的处理,避免原生换行被替换为<br>、空行被自动加<p>标签:
// 加入主题/插件的功能文件中
add_filter( 'the_content', function( $content ) {
    // 临时移除wpautop过滤,单独处理块内容
    remove_filter( 'the_content', 'wpautop' );
    $clean_content = wpautop( $content );
    add_filter( 'the_content', 'wpautop' );

    // 还原pre标签内的纯文本结构,清除内部冗余HTML标签
    return preg_replace_callback(
        '/<pre>(.*?)<\/pre>/s',
        function( $match ) {
            // 移除pre内部所有<br>、<p>标签,保留原生文本换行
            $inner_text = preg_replace( '/<br\s*\/?>|<p>|<\/p>/', '', $match[1] );
            return '<pre><code>' . trim( $inner_text ) . '</code></pre>';
        },
        $clean_content
    );
}, 9 );
  • 注册块时声明允许的标签规则,避免KSES安全过滤把pre、code内的内容转义为HTML实体:
// block.json配置补充
{
    "supports": {
        "html": true,
        "className": false, // 彻底关闭块自动追加class的能力
        "customClassName": false
    }
}

4. 存量问题验证

  • 检查MySQL中存储的块内容:正常状态下存储的代码内容应保留原生\n换行符,无冗余<br>、class=""类属性。
  • 前端渲染时,pre标签会自动识别内部的原生换行,不需要额外插入HTML标签即可实现代码块的正确断行展示。

内容的提问来源于stack exchange,提问作者user15393375

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.26 16:36:06