我同意 Jenne van der Meer 和 Nico Haase 的观点,即您的方法并不是特别理想。如果我可以选择,我会走一条不同的路线:不是在你的函数中渲染,而是在 twig 中渲染,然后将结果传递给函数(如{{ myFunc(form_label(form), form) }})。由于您忽略了您的功能实际需要和/或所做的事情,因此很难提供进一步的建议。但是,我绝对确定,可以在输入函数之前或之后通过宏/块,甚至可能是表单主题在 twig 中完成渲染。
但是,如果您真的需要您的函数来呈现表单字段...以下内容可能会对您有所帮助。我强烈建议不要这样做,可能有更合适的解决方案。
form_label 函数比简单函数稍微复杂一些。相反,it uses twig's compile mechanisms 到 generate specific php code。最终会call:
FormRenderer::searchAndRenderBlock(FormView $view, string $blockNameSuffix, array $variables = [])
深入编译器,模板调用form_label(form, options)会变成:
$this->env->getRuntime('Symfony\Component\Form\FormRenderer')->searchAndRenderBlock(
$form, 'label', $options
);
$this->env 似乎是树枝环境。这意味着,在你的树枝扩展 you need to have access to the proper Twig environment 中调用它,然后它应该已经可以使用我刚刚提供的配方了。特别是如果你可以省略 options 参数,我没有深入研究它是如何组装的(但它可能只是直截了当)。
所以你的 twig 函数必须通过以下方式定义:
public function getFunctions(): array
{
return [
new TwigFunction('myFunc', [&$this, 'myFunc'], [
'needs_environment' => true, // <--- this!
'is_safe' => ['html'],
]),
];
}
public function myFunc(\Twig\Environment $env, $field) {
// other stuff
$html = $env->getRuntime(\'Symfony\Component\Form\FormRenderer\')->searchAndRenderBlock(
$field, 'label', $options
);
return $html;
}