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

Shopware 6:如何在前端/主题(如页脚)添加自定义PHP代码

在Shopware 6中全局添加自定义PHP代码的最佳方案

问题描述

需要在Shopware 6商店的所有页面执行自定义PHP代码(可添加至页眉或页脚),示例代码如下:

<?php
for ($i=1; $i<=10; $i++) {
    echo 'hello world ' . $i . '<br>';
}
?>

尝试通过插件实现,但不清楚代码的具体集成位置,无法让代码在页脚或全局页面生效。

更新说明

  • 已移除用途相关内容,下方部分评论可忽略。

有效解决方案(@Feanor提供)

以下是完整复现步骤:

  1. 创建插件
    在控制台执行命令生成插件:
bin/console plugin:create YourPluginName

创建过程中仅需对「Subscriber Event」选项选择「是」,完成后刷新后台,安装并激活该插件。

  1. 修改订阅者文件
    打开插件目录下的MySubscriber.php,先添加命名空间引用:
use Shopware\Storefront\Event\StorefrontRenderEvent;

再将文件内原有代码替换为以下内容,用于在页面渲染前传递自定义数据到模板:

<?php

namespace YourPluginName\Subscriber;

use Shopware\Storefront\Event\StorefrontRenderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MySubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            StorefrontRenderEvent::class => 'onStorefrontRender'
        ];
    }

    public function onStorefrontRender(StorefrontRenderEvent $event): void
    {
        // 自定义PHP逻辑:生成1到10的数组
        $event->setParameter('customHelloWorld', range(1, 10));
    }
}
  1. 创建模板文件
    在插件目录下创建路径src/Resources/views/storefront/layout/footer/footer.html.twig,添加模板代码输出内容:
{% for i in customHelloWorld %}
    hello world {{ i }}<br>
{% endfor %}

内容的提问来源于stack exchange,提问作者XXL-Webdesign

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:20:21