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

如何从自定义Bundle中添加Twig-Globals?

自定义Symfony Bundle中添加Twig全局变量失败的解决方法

问题场景

尝试在自定义Bundle中添加Twig全局变量,让引用该Bundle的应用能全局访问,但加载Bundle内的twig.yaml配置时触发报错:

There is no extension able to load the configuration for "twig" (in "/var/www/myproject/vendor/johncorps/forms-bundle/src/DependencyInjection/../../config/packages/twig.yaml"). Looked for namespace "twig", found "none".

尝试的配置与代码

twig.yaml配置文件:

# config/packages/twig.yaml
twig:
    form_themes: ['@JohnCorpForms/forms/themes/bootstrap_4_layout_custom.html.twig']
    globals:
        testvar: 'foobar-linus'
        theme_ci: 'blue-grey'
        app_core: '@JohnCorpForms\Utils\Twig\AppTwigGlobals'

Bundle扩展加载代码:

namespace JohnCorp\FormsBundle\DependencyInjection;

Rent2buyFormsExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../../config'));
        $loader->load(__DIR__ . '/../../config/packages/twig.yaml');
    }
}

解决方案

通过实现Twig的GlobalsInterface自定义扩展类,再在Bundle中注册该扩展的方式解决:

  1. 创建自定义Twig扩展类(实现GlobalsInterface)
namespace JohnCorp\FormsBundle\Utils\Twig;

use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;

class TwigExtension extends AbstractExtension implements GlobalsInterface
{
    private RequestStack $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function getGlobals(): array
    {
        return [
            'testvar' => 'foobar-linus',
            'theme_ci' => 'blue-grey',
            'app_core' => new AppTwigGlobals($this->requestStack),
        ];
    }
}
  1. 在Bundle类中注册并注入该扩展
class JohnCorpFormsBundle extends AbstractBundle
{
    public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        parent::loadExtension($config, $container, $builder);

        $definition = $builder
            ->autowire('johncorpforms.twig_extension', TwigExtension::class)
            ->addTag('twig.extension');
    }
}

最后确保在Bundle的services.yaml中完成RequestStack的自动注入配置,之后即可在所有Twig模板中全局访问app_core.{functionName}等变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:30:59