Symfony2中所有控制器的某些常用部分

时间:2012-07-08 21:03:44

标签: php symfony doctrine-orm twig

我有布局,类似的东西:

{# ... #}
{% render 'PamilGooglePlusBundle:Default:sidebar' %}
{# ... #}
{{ globalVariable }}

PamilGooglePlusBundle:Default:sidebar中,我使用DBAL运行2个查询,生成我的用户和组列表。我在sidebarAction()中有函数,它给了我实际资源的名称:组或用户名。我想在模板的其他部分使用它。

我有些想法。我必须每次查询运行此方法并每次都获取其变量,该怎么做?我的意思是某种控制器方法总是这样做,所以我可以得到变量。

1 个答案:

答案 0 :(得分:2)

我解决了这个问题! ;)

简单地说,我们进行Twig扩展,在一些参数中注册init函数,在主模板中使用它,值是注册全局 - 就像在这段代码中一样:

<?php

namespace Pamil\GooglePlusBundle\Extension\Twig;

use Doctrine\DBAL\Connection;

class Sidebar extends \Twig_Extension
{
    private $dbal;

    private $init = false;

    public $data = array();

    // Specify parameters in services.yml
    public function __construct(Connection $dbal)
    {
        $this->dbal = $dbal;
    }

    public function sidebarInit($pathinfo)
    {
        // This function returns empty string only, cos you can use it only as 
        // {{ sidebarInit(app.request.info) }}, not in {% %}
        if ($this->init === true) {
            return '';
        }

        $this->data = $dbal->fetchAll("SELECT * FROM table");
        // for example:        
        $this->data['key'] = 'value';       

        $this->init = true;
        return '';
    }

    public function getFunctions()
    {
        return array(
                'sidebarInit' => new \Twig_Function_Method($this, 'sidebarInit'),
                );
    }

    public function getGlobals()
    {
        return array(
                'sidebar' => $this
                );
    }

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

现在是services.yml

parameters:
    pamil.google.plus.bundle.extension.twig.sidebar.class: Pamil\GooglePlusBundle\Extension\Twig\Sidebar

services:
  pamil.google.plus.bundle.extension.twig.sidebar:
     class: "%pamil.google.plus.bundle.extension.twig.sidebar.class%"
     arguments: ["@database_connection"] #specify arguments (DBAL Connection here)
     tags:
            - { name: twig.extension, alias: ExtensionTwigSidebar }

我们可以在模板中使用它,例如main.html.twig

{{ sidebarInit(app.request.pathinfo) }}
<html>
{# ... #}
{% include 'PamilGooglePlusBundle::sidebar.html.twig' %}

sidebar.html.twig

{{ sidebar.data.key }}
{# outputs 'value' #}

希望它会帮助别人;)