我想定义一个新的树枝功能“form_field”这使得form_label
,form_widget
和form_errors
。我不想重写,form_row
因为我已经出于不同的目的这样做了:form_row
还包装<div/>
了布局所需的容器。具体来说,我添加了引导类。
我为什么需要这个?通常我会使用,form_row
但是我有很多表单行,我想在同一行中放置两个或多个字段(例如“名字”和“姓氏”)。在这种情况下,我确定我的包裹<div/>
手工,但我不想写三个函数调用(form_label
,form_widget
和form_errors
)每次。
我试图指定一个自定义函数,但是在那里调用细枝函数时出现异常。对于此解决方案,我需要知道如何从自定义函数调用Twig函数。
我的第二次尝试是使Symfony的解决方案适合其自己的表单助手。我在供应商/symfony/symfony/src/Symfony/Bridge/Twig/Extension/FormExtension.php中找到了这一行:
new \Twig_SimpleFunction('form_widget', null, array('node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => array('html'))),
看起来像一个实际上只是渲染一个块的函数。当我在AppBundle中修改该行时,抛出了一个异常,其中Symfony声称未定义名为“ form_field”的块。但是,我在自定义表单模板中定义了此块:
{% use 'bootstrap_3_horizontal_layout.html.twig' %}
{%- block form_field -%}
{{- form_label(form) -}}
{{- form_widget(form) -}}
{{- form_errors(form) -}}
{%- endblock form_field -%}
声明树枝模板Form / form_field.html.twig:
{%- block form_field -%}
{{- form_label(form, label) -}}
{{- form_widget(form) -}}
{{- form_errors(form) -}}
{%- endblock form_field -%}
然后,我renderBlock
在Twig自定义函数中使用了该方法。这是描述了我树枝扩展文件在这里:
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
protected $environment;
private $template;
public function __construct(\Twig_Environment $env)
{
$this->environment = $env;
}
public function getFunctions()
{
return array(
'form_field' => new \Twig_SimpleFunction('form_field', array($this, 'formField'), array(
'is_safe' => array('html')
))
);
}
public function formField($form, $label = null)
{
$this->template = $this->environment->loadTemplate( '::Form/form_field.html.twig' );
return $this->template->renderBlock('form_field', array(
'form' => $form,
'label' => $label
));
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'app_extension';
}
}
我将DI容器配置为传递AppExtension服务的Twig_Environment:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
arguments:
- '@twig'
tags:
- { name: twig.extension }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句