如何为 Twig 定义全局变量何为、定义、全局变量、Twig

2023-09-06 23:42:27 作者:刻骨的爱

我正在使用一个用作表单布局的文件来覆盖某些元素(form_start、form_row 等).我像这样注册它:

I'm using a file serving as a form layout to overwrite certain elements (form_start, form_row, etc.). I register it like:

twig:
    - AcmeMainBundle:Form:formlayout.html.twig

有没有一种方法可以在其中使用与 form 一起提供的变量?

Is there a way to use in it my variables provided along with a form?

例如,当我发送到 index.html.twig

array ('form' => $formView, 'var' => $var);

Var 仅在 index.html.twig 中定义.

Var is defined only in index.html.twig.

那么如何让var定义在formlayout.html.twig

推荐答案

你可以使用 addGlobal() 方法.

例如在我使用的 BaseController 中:

For example in BaseController I use:

$this->get('twig')->addGlobal('is_test', $isTest);

所以在你的情况下你可能应该这样做:

so in your case you should probably do:

$this->get('twig')->addGlobal('var', $var);