我的一些选择选项中有一个硬空间(
)。不知何故,在某个地方,他们正在逃脱。我试过:
{% autoescape false %}
{{ form_widget(foobar) }}
{% endautoescape %}
以及
{{ form_widget(foobar)|raw }}
以及以下在 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到达特维格时,它已经逃脱了。做form_widget(foobar)|raw
表明了这一点。
编辑:我添加了一个解决方法作为答案,但我仍然有兴趣接受一个解释如何防止初始转义完全发生的答案。
我在收音机标签上遇到了同样的问题。 这就解决了。
{% for child in form %}
{% autoescape false %}
{{ child.vars.label }}
{% endautoescape %}
{{ form_widget(child) }}
{% endfor %}
我最终创建了一个 Twig 扩展,用于解码编码的 HTML 并将其添加为服务:
供应商/捆绑/扩展/树枝中的扩展
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';
}
}
在供应商/捆绑包/资源/配置/服务.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 %}
请注意添加的自动转义部分。
可能
不是最好的解决方案,但是在你的表单构造函数中这样做呢(我们强制
是一个空格字符):
public function __construct() {
foreach ($this->fooChoices as $key => $fooChoice) {
$this->fooChoices[$key] = html_entity_decode($fooChoice, ENT_NOQUOTES, 'UTF-8');
}
}