2012-07-08 26 views
2

某種類型的所有控制器的始終做一部分的我有佈局,這樣的事情:在Symfony2中

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

PamilGooglePlusBundle:Default:sidebar我使用DBAL其產生我的用戶和組的列表運行2個查詢。我有sidebarAction()函數,它給了我實際資源的名稱:組或用戶名。我想在模板的其他部分使用它。

我有些想法。我必須運行這個方法每個查詢,並獲得它的變量每次,如何做到這一點?我的意思是總是這樣做的一種控制器方法,以便我可以獲取變量。

+0

我不知道您的使用情況到底是什麼......但也許這會給一些洞察到一個可能的解決方案HTTP ://matt.drollette.com/2012/06/calling-a-method-before-every-controller-action-in-symfony2/ – MDrollette 2012-07-08 21:44:12

+0

@MDrollette他想顯示,例如,註冊用戶數,多次內他的佈局以及來自不同的渲染動作,而無需每次都請求數據庫。 – AdrienBrault 2012-07-09 00:22:23

+0

將它存儲在會話變量中,並且只在特定時間間隔或特定事件中刷新它? http://stackoverflow.com/questions/11165467/assign-a-global-twig-variable-in-symfony-2 – MDrollette 2012-07-09 00:27:50

回答

2

我解決了這個問題! ;)

簡單地說,我們做的樹枝延伸,在那裏註冊初始化函數一些參數,在主模板和值,用它的註冊全局變量 - 就像在這個代碼:

<?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' #} 

希望這將幫助別人;)