如何在Shopware6的Store-Front中获取插件配置plugin-config至FooterPagelet
1. 注入系统配置服务
在你的事件订阅类中,通过构造函数注入SystemConfigService——这是Shopware专门用来读取系统及插件配置的核心服务。
2. 读取插件配置
在addCustomfield方法里,用SystemConfigService的get方法拉取你的插件配置。配置键的格式固定为[插件技术名称].config.[配置项名称],比如插件叫MyCustomPlugin,配置项是footerNotice,那键就是MyCustomPlugin.config.footerNotice。
如果你的配置支持多销售渠道,记得传入当前销售渠道ID,确保读取到对应渠道的配置值。
3. 将配置添加到FooterPagelet
把读取到的配置数据通过addExtension方法挂载到FooterPagelet上,前端模板就能直接访问。
完整代码示例
use Shopware\Core\System\SystemConfig\SystemConfigService; use Shopware\Storefront\Pagelet\Footer\FooterPageletLoadedEvent; class FooterConfigSubscriber { private SystemConfigService $systemConfigService; // 构造函数注入服务 public function __construct(SystemConfigService $systemConfigService) { $this->systemConfigService = $systemConfigService; } public function addCustomfield(FooterPageletLoadedEvent $event): void { $salesChannelId = $event->getSalesChannelContext()->getSalesChannelId(); // 读取整个插件配置对象 $pluginConfig = $this->systemConfigService->get('MyCustomPlugin.config', $salesChannelId); // 将配置添加为FooterPagelet的扩展 $event->getPagelet()->addExtension('plugin_config', $pluginConfig); // 也可以单独读取某一个配置项 // $footerNotice = $this->systemConfigService->get('MyCustomPlugin.config.footerNotice', $salesChannelId); // $event->getPagelet()->addExtension('footer_notice', $footerNotice); } }
前端模板调用示例
在Storefront的footer模板(比如storefront/layout/footer/footer.html.twig)中,这样访问配置:
{# 访问整个插件配置对象里的具体项 #} {{ page.footer.extensions.plugin_config.footerNotice }} {# 如果是单独添加的单个配置项 #} {{ page.footer.extensions.footer_notice }}
注意事项
- 要确保你的插件已经在
src/Resources/config/config.xml中正确定义了配置项,这样后台才能显示并允许编辑这些配置。 - 如果配置不需要区分销售渠道,可以忽略第二个参数,直接调用
get('MyCustomPlugin.config.footerNotice')。
内容的提问来源于stack exchange,提问作者Muhammad Zahoor
相关产品推荐
相关产品推荐

