Twig and autoescaping

2019-05-16 23:04发布

问题:

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 }}