You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6 Twig中如何解码商品描述内的HTML实体?

Shopware 6 Twig解码HTML实体的几种方法

针对你遇到的商品描述里HTML实体(比如&)无法用|raw解码,且Twig自带没有|html_entity_decode过滤器的问题,给你几个实用方案:

  • 自定义Twig过滤器(最推荐)
    Shopware 6支持自行添加Twig过滤器,步骤很简单:

    1. 在你的插件里新建一个Twig扩展类,比如HtmlEntityDecodeExtension.php,代码如下:
    <?php
    namespace YourPluginNamespace\Twig;
    
    use Twig\Extension\AbstractExtension;
    use Twig\TwigFilter;
    
    class HtmlEntityDecodeExtension extends AbstractExtension
    {
        public function getFilters(): array
        {
            return [
                new TwigFilter('html_entity_decode', [$this, 'decode']),
            ];
        }
    
        public function decode(string $content): string
        {
            return html_entity_decode($content, ENT_QUOTES, 'UTF-8');
        }
    }
    
    1. 在插件的services.xml里注册这个扩展:
    <service id="YourPluginNamespace\Twig\HtmlEntityDecodeExtension" public="true">
        <tag name="twig.extension"/>
    </service>
    

    完成后,模板里直接用{{ product.description|html_entity_decode }}即可,和原生过滤器用法一致。

  • 直接调用PHP原生函数
    Twig默认允许调用部分PHP全局函数,试试在模板里直接写:

    {{ html_entity_decode(product.description, ENT_QUOTES, 'UTF-8') }}
    

    只要Shopware没限制这个函数的调用,就能直接生效,省去编写插件代码的步骤。

  • 导出前提前处理数据
    如果是做Feed导出,也可以在获取商品数据的环节提前处理,比如在你的Feed生成服务类里:

    $decodedDesc = html_entity_decode($product->getDescription(), ENT_QUOTES, 'UTF-8');
    

    把处理后的描述传给模板,模板里直接输出即可,无需再使用过滤器。

  • 用|striptags(适合纯文本场景)
    如果你的Feed只需要纯文本、不需要保留HTML标签,直接用|striptags就行——它会自动把实体转成正常字符,同时去掉所有HTML标签:

    {{ product.description|striptags }}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:10:05