Shopware 6.5.4.0中Twig环境注入失败及自定义Twig函数问题求助
问题分析与解决方案
核心错误原因
- 控制器注入方式错误:继承
StorefrontController后,不能通过自定义构造函数注入Twig,Shopware的Storefront控制器体系依赖setter注入而非构造函数参数。 - Twig扩展未注册:自定义的
StoryblokTwigExtension未在services配置中注册并添加Twig扩展标签,导致get_story函数无法被Twig识别。 - 服务配置不匹配:控制器的service定义错误,未按Shopware要求使用
setTwig方法注入Twig实例。
修复步骤
1. 修正控制器代码
删除自定义构造函数,直接使用StorefrontController父类提供的Twig实例:
<?php declare(strict_types=1); namespace Nst\Storefront\Controller; use Shopware\Storefront\Controller\StorefrontController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route(defaults={"_routeScope"={"storefront"}}) */ class CodesController extends StorefrontController { /** * @Route("/mystore", name="frontend.example.example", methods={"GET"}, defaults={"_routeScope"={"storefront"}}) */ public function showPage(): Response { // 父类已自动注入Twig,直接调用renderStorefront即可 return $this->renderStorefront('@Nst/storefront/page/example.html.twig', [ 'example' => 'Hello world' ]); } }
2. 更新services.xml配置
添加Twig扩展注册,修正控制器的Twig注入方式:
<?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services"> <services> <service id="Nst\Service\StoryblokService" public="true"> <argument type="service" id="Storyblok\Client"/> </service> <service id="Storyblok\Client" class="Storyblok\Client"> <argument>%env(storyblok_api_key)%</argument> <!-- 确保.env文件中配置了STORYBLOK_API_KEY变量 --> </service> <!-- 注册Twig扩展,必须添加twig.extension标签 --> <service id="Nst\Twig\StoryblokTwigExtension" public="false"> <argument type="service" id="Nst\Service\StoryblokService"/> <tag name="twig.extension"/> </service> <service id="Nst\Storefront\Controller\CodesController" public="true"> <call method="setContainer"> <argument type="service" id="service_container"/> </call> <!-- 使用setTwig方法注入Twig,符合StorefrontController规范 --> <call method="setTwig"> <argument type="service" id="twig"/> </call> </service> </services> </container>
3. 确保StoryblokService实现正确
补充StoryblokService的核心逻辑(若未实现):
<?php declare(strict_types=1); namespace Nst\Service; use Storyblok\Client; class StoryblokService { public function __construct(private Client $storyblokClient) { } public function getStory(string $slug): array { // 调用Storyblok API获取数据 $response = $this->storyblokClient->getStoryBySlug($slug); return $response['data']['story'] ?? []; } }
验证修复
- 清除Shopware缓存:执行
bin/console cache:clear - 访问
/mystore页面,检查Twig模板中的get_story函数是否能正常获取并渲染Storyblok数据 - 确认控制器无注入相关报错
内容的提问来源于stack exchange,提问作者tee
相关产品推荐
相关产品推荐

