mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-15 20:06:31 +00:00
minor #1333 Added disambiguation on using raw in expressions (OwlyCode)
This PR was merged into the 1.16-dev branch.
Discussion
----------
Added disambiguation on using raw in expressions
I recently got in trouble using the ``raw`` filter in a ternary, leading to a value being escaped and me not expecting it. The code was :
```
{{ foo|striptags|length > 250 ? foo|striptags|slice(0, 250) ~ '...' : foo|raw }}
```
When foo's length was under 250 characters, the result of this expression was escaped. Here is the updated documentation to explain why.
Commits
-------
cec2b57 Added disambiguation on using raw in expressions
This commit is contained in:
@@ -10,3 +10,27 @@ if ``raw`` is the last filter applied to it:
|
||||
{% autoescape %}
|
||||
{{ var|raw }} {# var won't be escaped #}
|
||||
{% endautoescape %}
|
||||
|
||||
.. note::
|
||||
|
||||
Be careful when using the ``raw`` filter inside expressions. This
|
||||
snippet illustrates a case that can be confusing :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{% autoescape %}
|
||||
{% set hello = '<strong>Hello</strong>' %}
|
||||
{% set hola = '<strong>Hola</strong>' %}
|
||||
|
||||
{{ false ? '<strong>Hola</strong>' : hello|raw }}
|
||||
does not render the same as
|
||||
{{ false ? hola : hello|raw }}
|
||||
but renders the same as
|
||||
{{ (false ? hola : hello)|raw }}
|
||||
{% endautoescape %}
|
||||
|
||||
The first ternary won't be escaped : ``hello`` is marked as being safe and
|
||||
Twig does not escape static values (see :doc:`escape<../tags/autoescape>`).
|
||||
In the second ternary, even if ``hello`` is marked as safe, ``hola``
|
||||
remains unsafe and so will be the whole expression. On the other hand, the
|
||||
third ternary will be marked as safe and the result won't be escaped.
|
||||
+14
-1
@@ -65,7 +65,20 @@ Functions returning template data (like :doc:`macros<macro>` and
|
||||
Twig is smart enough to not escape an already escaped value by the
|
||||
:doc:`escape<../filters/escape>` filter.
|
||||
|
||||
.. note::
|
||||
|
||||
Twig does not escape static expressions :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{% set hello = "<strong>Hello</strong>" %}
|
||||
{{ hello }}
|
||||
{{ "<strong>world</strong>" }}
|
||||
|
||||
Will be rendered "<strong>Hello</strong> **world**".
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
The chapter :doc:`Twig for Developers<../api>` gives more information
|
||||
about when and how automatic escaping is applied.
|
||||
about when and how automatic escaping is applied.
|
||||
Reference in New Issue
Block a user