Twig and autoescaping

一个人想着一个人 提交于 2019-12-07 13:38:26

问题


I'm learning Symfony2. Currently, I'm trying to render a form label in a twig template. The label includes an html tag, that is not rendered correctly in my twig file.

Here follows the piece of code where the form field is created:

$builder->add('zipcode', 'integer', array(
        'label' => '<abbr title="Zone Improvement Plan">CAP</abbr> code',
        ));

In the twig file I render the field label as follows:

{{ form_label(form.zipcode) }}

I tried the raw, escape, e filters, but the results provided in my html page is always the string

 <abbr title="Zone Improvement Plan">CAP</abbr> code

and not the corresponding HTML code!

Any suggestion? Thanks in advance!

Later I found the solution. The solution is to disable the autoescape within the label block provided by Symfony at path: symfony / src / Symfony / Bridge / Twig / Resources / views / Form / form_div_layout.html.twig

So, in your twig file you have to put the following lines outside the form: {% form_theme form _self %}

{% block generic_label %}
{% spaceless %}
  {% if required %}
      {% set attr = attr|merge({'class': attr.class|default('') ~ ' required'}) %}
  {% endif %}
  <label{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>{% autoescape false %}{{ label|trans }}{% endautoescape %}</label>
{% endspaceless %}
{% endblock %}

回答1:


From JeanValjean himself :

{% autoescape false %}{{ form.zipcode.vars.label | trans }}{% endautoescape %}

And to generalize this behaviour to your whole app, you can override the form block for labels :

{% block generic_label %}
    {% spaceless %}
        {% if required %}
            {% set attr = attr|merge({'class': attr.class|default('') ~ ' required'}) %}
        {% endif %}
        <label{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>
            {% autoescape false %}{{ label|trans }}{% endautoescape %}
        </label>
    {% endspaceless %}
{% endblock %}



回答2:


To disable the autoespace filter just to render a variable is not the best thing because when you read the code it's not really clear.

So, instead of :

{% autoescape false %}{{ label|trans }}{% endautoescape %}

You can use :

{{ label|trans|raw }}



来源:https://stackoverflow.com/questions/10209345/twig-and-autoescaping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!