配置HTML Sanitizer允许SVG失败,遇HTMLPurifier报错
解决Shopware HTML Sanitizer允许SVG元素的问题
你遇到的核心问题是:HTMLPurifier默认不内置SVG元素的支持,仅通过Shopware的yaml配置添加标签无法让HTMLPurifier识别SVG,所以会抛出Element 'svg' is not supported的错误。需要通过代码扩展HTMLPurifier的元素定义,再配合配置完成设置。
步骤1:注册SVG元素到HTMLPurifier
创建一个事件订阅器,在HTMLPurifier初始化时注册SVG及其子元素的定义:
<?php namespace YourPluginNamespace\Subscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Shopware\Core\Framework\Event\BeforeSendResponseEvent; use HTMLPurifier_Config; class SvgSanitizerSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ BeforeSendResponseEvent::class => 'registerSvgElements', ]; } public function registerSvgElements(): void { $config = HTMLPurifier_Config::createDefault(); $htmlDef = $config->getHTMLDefinition(true); // 注册根svg元素 $htmlDef->addElement( 'svg', 'Block', 'Flow', 'Common', [ 'width' => 'Length', 'height' => 'Length', 'viewBox' => 'Text', 'xmlns' => 'Text', 'fill' => 'Text' ] ); // 按需注册SVG子元素(比如path、circle等) $htmlDef->addElement( 'path', 'Inline', 'Empty', 'Common', [ 'd' => 'Text', 'fill' => 'Text', 'stroke' => 'Text', 'stroke-width' => 'Number' ] ); } }
步骤2:注册订阅器服务
在插件的src/Resources/config/services.xml中添加服务注册:
<?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> <service id="YourPluginNamespace\Subscriber\SvgSanitizerSubscriber"> <tag name="kernel.event_subscriber"/> </service> </services> </container>
步骤3:更新Shopware HTML Sanitizer配置
修改config/packages/shopware.yaml(或自定义插件的配置文件),允许SVG及其属性:
shopware: html_sanitizer: sets: - name: basic tags: ["svg", "path"] # 包含需要允许的SVG元素 attributes: svg: ["width", "height", "viewBox", "xmlns", "fill"] path: ["d", "fill", "stroke", "stroke-width"] options: - key: HTML.Trusted value: true
说明
- HTMLPurifier需要明确知道每个元素的类型、内容模型和允许的属性,所以必须通过代码注册SVG元素的定义,仅靠yaml配置无法生效。
- 如果你需要支持更多SVG子元素(如circle、rect、text等),可以在订阅器中用
addElement方法逐一注册,并在yaml配置中添加对应的标签和属性。
内容的提问来源于stack exchange,提问作者Ezycod
相关产品推荐
相关产品推荐

