[英]Symfony2 Formbuilder auto escaping?
我的一些选择选项中有一个硬空间(
)。 不知何故,在某个地方,他们正在逃脱。 我试过了:
{% autoescape false %}
{{ form_widget(foobar) }}
{% endautoescape %}
以及
{{ form_widget(foobar)|raw }}
以及在config.yml
Twig下面的config.yml
autoescape: false
然而,选择字段仍然呈现为 Choice Text Here
而不是Choice Text Here
,并且在源中它们被编码为 Choice Text Here
在控制器中我有:
$form ->add('foo', 'choice', array(
'label' => 'Foo Label',
'choices' => $fooChoices,
'required' => true));
$form = $form->getForm();
$foobar = $form->createView();
如果我print_r
$fooChoices
我得到:
Array ( [1] => 60# FooBar [5] => 60# BatBar [11] => 60# DooWop )
哪个显示我正确的
(注意60年代前面的双重空间)。 在FormBuilder和渲染之间的某个地方,它会被转义。
表单生成器内部是否存在内置转义?
我所推断的是,通过$form->createView()
呈现表单视图,数据仍未转义。 但是,当它通过form_widget到达Twig时,它已被转义。 执行form_widget(foobar)|raw
显示此信息。
编辑:我已经添加了一个解决方法作为答案,但我仍然有兴趣接受一个解释如何防止最初的逃避完全发生的答案。
我遇到了无线电标签的同样问题。 这解决了它。
{% for child in form %}
{% autoescape false %}
{{ child.vars.label }}
{% endautoescape %}
{{ form_widget(child) }}
{% endfor %}
我最终创建了一个Twig扩展,解码编码的HTML并将其添加为服务:
Vendor / Bundle / Extensions / Twig中的扩展
namespace Vendor\Bundle\Extensions\Twig;
class HTMLDecodeTwigExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
'htmldecode' => new \Twig_Filter_Method($this, 'htmldecode', array(
'is_safe' => array('html'))
),
);
}
// your custom function
public function htmldecode($string)
{
return html_entity_decode($string);
}
// Name for Service
public function getName()
{
return 'html_decode_twig_extension';
}
}
在Vendor / Bundle / Resources / config / services.yml中注册服务
vendor_bundle.htmldecode:
class: Vendor\Bundle\Extensions\Twig\HTMLDecodeTwigExtension
tags:
- { name: twig.extension }
用法:
{{ form_widget(foobar)|htmldecode }}
我仍然不知道在哪里执行转义,因为它只在数据本身上执行(我尝试创建一个数据事件来修改表单的数据),但这至少给了我最终结果我正在寻找对于。
你真正应该做的是覆盖form_label模板
{% block form_label %}
{% spaceless %}
{% if label is not sameas(false) %}
{% if not compound %}
{% set label_attr = label_attr|merge({'for': id}) %}
{% endif %}
{% if required %}
{% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' required')|trim}) %}
{% endif %}
{% if label is empty %}
{% set label = name|humanize %}
{% endif %}
{% autoescape false %}<label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>{{ label|trans({}, translation_domain) }}</label>{% endautoescape %}
{% endif %}
{% endspaceless %}
{% endblock form_label %}
请注意添加autoescape部分。
也许不是最好的解决办法,但怎么样做,在你的表单构造(我们强制
是一个空格字符):
public function __construct() {
foreach ($this->fooChoices as $key => $fooChoice) {
$this->fooChoices[$key] = html_entity_decode($fooChoice, ENT_NOQUOTES, 'UTF-8');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.