Symfony 2.0.3全局模板变量

Leo*_*ley 21 symfony twig

我有一个我想与用户会话关联的实体.我创建了一项服务,以便我可以从何处获取此信息.

在服务中我将实体id保存在会话变量中,并且在getEntity()方法中我得到会话变量并且使用doctrine找到实体并返回它.

这种方式到模板我应该可以调用 {{ myservice.myentity.myproperty }}

问题是myservice在整个地方都被使用了,我不想在每个Action中都得到它并将它附加到视图数组.

有没有办法让会话等所有视图都可以访问服务{{ app.session }}

Leo*_*ley 49

解决方案

通过创建自定义服务,我可以从任何地方使用

$this->get('myservice');
Run Code Online (Sandbox Code Playgroud)

这一切都是通过http://symfony.com/doc/current/book/service_container.html完成的

但我会给你一些演示代码.

服务

第一个片段是实际服务

<?php
namespace MyBundle\AppBundle\Extensions;

use Symfony\Component\HttpFoundation\Session;
use Doctrine\ORM\EntityManager;
use MyBundle\AppBundle\Entity\Patient;

class AppState
{
    protected $session;
    protected $em;

    function __construct(Session $session, EntityManager $em)
    {
        $this->session = $session;
        $this->em = $em;
    }

    public function getPatient()
    {
        $id = $this->session->get('patient');
        return isset($id) ? $em->getRepository('MyBundleStoreBundle:Patient')->find($id) : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

config.yml用这样的东西在你身上注册

services:
    appstate:
        class: MyBundle\AppBundle\Extensions\AppState
        arguments: [@session, @doctrine.orm.entity_manager]
Run Code Online (Sandbox Code Playgroud)

现在我们可以像之前说过的那样,在我们的控制器中获得服务

$this->get('myservice');
Run Code Online (Sandbox Code Playgroud)

但由于这是一项全球服务,我不想在每个控制器和每个操作中都这样做

public function myAction()
{
    $appstate = $this->get('appstate');
    return array(
        'appstate' => $appstate
    );
}
Run Code Online (Sandbox Code Playgroud)

所以现在我们去创建一个Twig_Extension

树枝延伸

<?php
namespace MyBundle\AppBundle\Extensions;

use MyBundle\AppBundle\Extensions\AppState;

class AppStateExtension extends \Twig_Extension
{
    protected $appState;

    function __construct(AppState $appState) {
        $this->appState = $appState;
    }

    public function getGlobals() {
        return array(
            'appstate' => $this->appState
        );
    }

    public function getName()
    {
        return 'appstate';
    }

}
Run Code Online (Sandbox Code Playgroud)

通过使用依赖注入,我们现在拥有我们在名为appstate的twig扩展中创建的AppState服务

现在我们用symfony注册它(再次在servicesconfig文件中的部分内)

twig.extension.appstate:
    class: MyBundle\AppBundle\Extensions\AppStateExtension
    arguments: [@appstate]
    tags:
        - { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)

重要的部分是"标签",因为这是symfony用于查找所有树枝扩展的内容

我们现在设置为通过变量名在我们的twig模板中使用我们的appstate

{{ appstate.patient }}
Run Code Online (Sandbox Code Playgroud)

要么

{{ appstate.getPatient() }}
Run Code Online (Sandbox Code Playgroud)

真棒!

  • 请考虑在Sf2文档中根据此答案创建一本食谱文章. (6认同)