如何将全局变量注入所有模板? [英] How to inject global variables into all templates?

查看:23
本文介绍了如何将全局变量注入所有模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 twig 模板中,每个页面都需要一些变量,例如 userNameuserIduserImage.

In my twig template there are some variables that are required on each page like userName, userId or userImage.

将它们注入模板的最佳方法是什么?

What is the best way to inject them into the template?

我已经阅读了文章如何将变量注入所有模板但是我如何将变量(例如当前用户)写入 config/packages/twig.php 文件?

I already read the article How to Inject Variables into all Templates but how could I write a variable (e.g. current user) into the config/packages/twig.php file?

现在每个控制器中都有这样的代码:

Right now there is code like this in every controller:

return $this->render('admin/users/index.html.twig', [
   "allUsers" => $allUsers,
   "pageTitle" => "Benutzerübersicht",
   "userName" => "Max Mustermann",
   "userId" => 5,
   "userImage" => "http://i.pravatar.cc/150?img=6"
]);

(这些只是示例值,因为我还没有集成身份验证但想创建我的模板)

(These are only example values as I didn't integrate the Authentication yet but wanted to create my template)

有没有比在每个控制器中注入每个变量更好的方法?

Is there any better way than injecting every variable in each controller?

推荐答案

您有多种选择,具体取决于您的需要:

You have several options, depending exactly on what do you need:

  1. 创建一个监听器类:

namespace App\Listener;
// src/EventListener/ControllerListener.php

use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;

class ControllerListener {
    /**
     * @var \Twig\Environment
     */
    private $twig;
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $manager;
    /**
     * @var \Symfony\Component\Security\Core\Security
     */
    private $security;

    public function __construct( Environment $twig, EntityManager $manager, Security $security ) {
        $this->twig     = $twig;
        $this->manager  = $manager;
        $this->security = $security;
    }

    public function onKernelController( FilterControllerEvent $event ): void {
        $results = $this->manager->getRepository( 'SomeClass' )->findBy( [ 'some' => 'criteria' ] );
        $user    = $this->security->getUser();
        $this->twig->addGlobal( 'veryGlobal', $results[0]->getName() );
        $this->twig->addGlobal( 'username', $user->getUsername() );
    }
}

我正在注射:

  • Twig,所以你可以在那里添加全局变量.
  • 实体管理器,如果您需要从那里获取信息,您可以查询数据库
  • 安全,从用户那里获取信息.

  • Twig, so you can add the global variables there.
  • Entity Manager, so you can query the DB if you need to grab info from there
  • Security, to grab information from the user.

  1. 创建完成后,您需要添加以下配置行:

# config/services.yaml
services:
    App\EventListener\ControllerListener:
        tags:
            - { name: kernel.event_listener, event: kernel.controller }

这将使事件侦听器能够在每个请求上运行.

which will enable the event listener to run on each request.

使用这些配置行,如文档中所述,你告诉 twig 注入一个特定的服务:

With these configuration lines, as described in the documentation, you tell twig to inject a specific service:

# config/packages/twig.yaml
twig:
    # ...
    globals:
        # the value is the service's id
        users: '@App\Service\UserManagement'

然后就像创建App\Service\UserManagement一样简单:

Then it's as simple as creating App\Service\UserManagement:

namespace App\Service:

class UserManagement {

   public function __construct() {
      // use the constructor to inject your dependencies, as usual
   }

   public function getOldestUser() {
      // do your thing
      return $oldestUserName;
   }
}

然后从树枝你可以做:

{{ users.oldestUser }}

最后,如果您只对登录的用户数据感兴趣

正如其他人提到的,如果您只对属于登录用户的数据感兴趣,您可以简单地访问它通过在每个请求中注入的 app 变量.

当前用户的表示,如果没有则为null.存储在此变量中的值可以是 UserInterface 对象、任何其他实现 __toString() 方法的对象,甚至是常规字符串.

The representation of the current user or null if there is none. The value stored in this variable can be a UserInterface object, any other object which implements a __toString() method or even a regular string.

例如:

{{ app.user.userName }}

这篇关于如何将全局变量注入所有模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆