[英]Symfony2 custom form renderer helper function
我想定義一個新的樹枝函數“form_field”,它呈現form_label
、 form_widget
和form_errors
。 我不想覆蓋form_row
因為我已經出於不同的目的這樣做了: form_row
還包裝了我的布局所需的<div/>
容器。 具體來說,我添加了引導程序類。
為什么我需要這個? 通常我使用form_row
但我有很多表單行,我想在同一行中放置兩個或更多字段(例如“名字”和“姓氏”)。 在這些情況下,我手動定義了我的包裝<div/>
,但我不想每次都編寫三個函數調用( form_label
、 form_widget
和form_errors
)。
我試圖指定一個自定義函數,但在那里調用樹枝函數時出現異常。 對於這個解決方案,我需要知道如何從自定義函數調用 Twig 函數。
我的第二次嘗試是將 Symfony 的解決方案調整為它自己的表單助手。 我在 vendor/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 -%}
然后我在我的 Twig 自定義函數中使用了renderBlock
方法。 這是描述了我樹枝擴展文件在這里:
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 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.