yevg
yevg

Reputation: 1966

Global raw escaping in Twig

Is it possible to set a directive that every variable in a Twig template within a certain scope will be escaped with the raw filter?

Ex.

{% setAllRaw %}

    {{foo}} // this will be rendered as if foo|raw
    {{bar}} // this will be rendered as if bar|raw
    {{baz}} // this will be rendered as if baz|raw

{% endSetAllRaw %}

Instead of having to explicitly write

    {{foo|raw}} 
    {{bar|raw}}
    {{baz|raw}}

It would be great if this was inherited by child templates..

{% setAllRaw %}

    {{foo}} // this will be rendered as if foo|raw
    {% include 'component.twig' %} // every variable in this template will also be rendered as raw

{% endSetAllRaw %}

** AND/OR **

Is there a way to indicate in the controller that a variable is to be rendered as raw

Ex.

// Controller

$data['foo'] = renderAsRaw($foo);

return new Response($this->renderView('template.html.twig', $data));

// Template

{{foo}} // will be rendered as raw

I tried using the autoescape but this does not work as I have described above

{% autoescape %}
    {{foo}} // this does NOT render as raw
{% endautoescape %}

Upvotes: 0

Views: 851

Answers (1)

Michael Sivolobov
Michael Sivolobov

Reputation: 13240

All your templates by default use autoescaping.

You can disable autoescape for part of your template by adding false in autoescape block declaration:

{% autoescape false %}
    {{ rawVar }}
{% endautoescape %}

If you need to disable autoescaping in all your templates you can set global parameter in config.yml:

twig:
    autoescape: false

Upvotes: 3

Related Questions