[英]How to define global variables for Twig templates with values coming from the DB?
我想為 twig 定義一個全局變量,它可以從任何模板訪問。
我可以在 symfony 的config/packages/twig.yaml
創建一個全局變量,但我需要它是從數據庫中獲取的值。
在樹枝的文檔中,它說要使用此代碼:
$twig = new Twig_Environment($loader);
$twig->addGlobal('name', 'value');
我應該在哪里使用此代碼,以便此變量可用於每個模板?
一種相對干凈的方法是添加一個事件訂閱者 ,它將在實例化控制器之前全局注入變量。
做控制器,所建議的意見,一個問題是,你的全局不會是全球所有,但只對控制器進行定義。
你可以這樣做:
// src/Twig/TwigGlobalSubscriber.php
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class TwigGlobalSubscriber implements EventSubscriberInterface {
/**
* @var \Twig\Environment
*/
private $twig;
/**
* @var \Doctrine\ORM\EntityManager
*/
private $manager;
public function __construct( Environment $twig, EntityManager $manager ) {
$this->twig = $twig;
$this->manager = $manager;
}
public function injectGlobalVariables( GetResponseEvent $event ) {
$whatYouWantAsGlobal = $this->manager->getRepository( 'SomeClass' )->findBy( [ 'some' => 'criteria' ] );
$this->twig->addGlobal( 'veryGlobal', $whatYouWantAsGlobal[0]->getName() );
}
public static function getSubscribedEvents() {
return [ KernelEvents::CONTROLLER => 'injectGlobalVariables' ];
}
}
我故意模糊的數據庫交互,因為只有你確切知道你想從數據庫中檢索什么。 但是您要在此訂閱服務器上注入實體管理器,因此只需檢索相應的存儲庫並執行相應的搜索即可。
完成后,您可以從您的枝條模板中執行以下操作:
<p>I injected a rad global variable: <b>{{ veryGlobal }}</b></p>
Symfony 5.4 代碼
服務.yml:
App\Twig\TwigGlobalSubscriber:
tags:
- { name: kernel.event_listener, event: kernel.request }
SysParams - 我的服務從數據庫中獲取數據
src\\Twig\\TwigGlobalSubscriber.php
<?php
namespace App\Twig;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
use App\Service\SysParams;
class TwigGlobalSubscriber implements EventSubscriberInterface {
private $twig;
public function __construct( Environment $twig, SysParams $sysParams ) {
$this->twig = $twig;
$this->sysParams = $sysParams;
}
public function injectGlobalVariables() {
$base_params = $this->sysParams->getBaseForTemplate();
foreach ($base_params as $key => $value) {
$this->twig->addGlobal($key, $value);
}
}
public static function getSubscribedEvents() {
return [ KernelEvents::CONTROLLER => 'injectGlobalVariables' ];
}
public function onKernelRequest()
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.