我希望在渲染所有模板之后(或期间)修改模板块,但我还需要知道每个模板和块的名称。
考虑这两个模板:
//master.twig
{% block hello %}
{% endblock %}
//and page.twig
{% extends 'master.twig' %}
{% block hello %}
{% endblock %}
$twig->render('page.twig');
在此之后(或期间),我想更改内容。
的伪代码:
$template->blocks['master.twig']['hello'] .= 'append something';
如何做到这一点?
看起来Twig_NodeVisitorInterface
可以毫不费力地修改节点。
但是,要获取当前模板的名称,我将Twig_Environment
子类化为:
class TwigEnvironment extends \Twig_Environment
{
protected $currentTemplateName = null;
public function compileSource($source, $name = null)
{
$this->currentTemplateName = $name;
return parent::compileSource($source, $name);
}
public function getCurrentTemplateName()
{
return $this->currentTemplateName;
}
}
看起来这样可行!