本文目录导读:

- 在
config/packages/twig.yaml中配置 - 通过 Twig Extension 动态设置
- 通过 Event Listener/Subscriber
- 全局变量的实用示例
- 调试全局变量
- 最佳实践建议
在 Symfony 项目中使用 Twig 全局变量,有几种常用的方法:
在 config/packages/twig.yaml 中配置
这是最简单的静态全局变量设置方式:
# config/packages/twig.yaml
twig:
globals:
site_name: '我的网站'
ga_tracking: 'UA-XXXXX-X'
version: '1.0.0'
在模板中使用:
<h1>{{ site_name }}</h1>
<script>ga('create', '{{ ga_tracking }}', 'auto');</script>
通过 Twig Extension 动态设置
更适合需要动态计算或依赖服务的全局变量:
// src/Twig/AppExtension.php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;
class AppExtension extends AbstractExtension implements GlobalsInterface
{
private $someService;
public function __construct(SomeService $someService)
{
$this->someService = $someService;
}
public function getGlobals(): array
{
return [
'current_user' => $this->someService->getCurrentUser(),
'menu_items' => $this->someService->getMenuItems(),
'app_version' => $this->getAppVersion(),
];
}
private function getAppVersion(): string
{
// 动态获取版本号
return exec('git describe --tags') ?: 'dev';
}
}
注册服务:
# config/services.yaml
services:
App\Twig\AppExtension:
tags: ['twig.extension']
通过 Event Listener/Subscriber
在控制器执行前设置全局变量:
// src/EventListener/TwigGlobalsListener.php
namespace App\EventListener;
use Twig\Environment;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
class TwigGlobalsListener
{
private $twig;
public function __construct(Environment $twig)
{
$this->twig = $twig;
}
public function onKernelController(ControllerEvent $event)
{
// 只在主请求中添加
if (!$event->isMainRequest()) {
return;
}
$this->twig->addGlobal('request_time', time());
$this->twig->addGlobal('is_ajax', $event->getRequest()->isXmlHttpRequest());
}
}
注册 listener:
# config/services.yaml
services:
App\EventListener\TwigGlobalsListener:
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
全局变量的实用示例
用户信息与导航
class AppExtension extends AbstractExtension implements GlobalsInterface
{
public function getGlobals(): array
{
return [
'user' => $this->getUser() ?? null,
'navigation' => [
'main' => [
['label' => '首页', 'path' => 'home'],
['label' => '产品', 'path' => 'product_list'],
['label' => '#39;, 'path' => 'about'],
],
'admin' => [
['label' => '仪表盘', 'path' => 'admin_dashboard'],
['label' => '用户管理', 'path' => 'admin_users'],
],
],
'config' => [
'site' => [
'title' => 'My Symfony App',
'description' => 'A great app',
],
'features' => [
'dark_mode' => true,
'comments' => false,
],
],
];
}
}
在模板中使用
{# 布局模板 #}
<nav>
{% if user %}
<span>欢迎, {{ user.username }}</span>
<a href="{{ path('logout') }}">退出</a>
{% else %}
<a href="{{ path('login') }}">登录</a>
{% endif %}
{% for item in navigation.main %}
<a href="{{ path(item.path) }}">{{ item.label }}</a>
{% endfor %}
</nav>
{# 使用配置 #}{{ config.site.title }}</title>
<meta name="description" content="{{ config.site.description }}">
{# 条件特性 #}
{% if config.features.dark_mode %}
<link rel="stylesheet" href="dark-mode.css">
{% endif %}
调试全局变量
查看所有可用的全局变量:
{{ dump(_context) }}
或使用 Web Profiler 的 Twig 面板查看。
最佳实践建议
- 不要过度使用全局变量 - 除非在大多数模板中都需要的变量
- 区分静态和动态全局变量:
- 静态配置(站点名称等)放在
twig.yaml - 动态数据(用户信息等)用 Extension 方式
- 静态配置(站点名称等)放在
- 命名规范 - 使用清晰的前缀避免冲突:
app_开头的应用级变量site_开头的站点配置
- 性能考虑 - 避免在全局变量中加载大量数据
选择哪种方式取决于你的具体需求:简单的静态配置用 yaml,需要依赖注入或动态计算的用 Extension,需要在请求生命周期特定时机设置的用 Event Listener。