我解決了這個問題! ;)
簡單地說,我們做的樹枝延伸,在那裏註冊初始化函數一些參數,在主模板和值,用它的註冊全局變量 - 就像在這個代碼:
<?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' #}
希望這將幫助別人;)
我不知道您的使用情況到底是什麼......但也許這會給一些洞察到一個可能的解決方案HTTP ://matt.drollette.com/2012/06/calling-a-method-before-every-controller-action-in-symfony2/ – MDrollette 2012-07-08 21:44:12
@MDrollette他想顯示,例如,註冊用戶數,多次內他的佈局以及來自不同的渲染動作,而無需每次都請求數據庫。 – AdrienBrault 2012-07-09 00:22:23
將它存儲在會話變量中,並且只在特定時間間隔或特定事件中刷新它? http://stackoverflow.com/questions/11165467/assign-a-global-twig-variable-in-symfony-2 – MDrollette 2012-07-09 00:27:50