我解决了这个问题!;)
简单地说,我们做 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' #}
希望它会帮助别人;)