Skip to content

Commit

Permalink
minor #4324 [Doc] Document about html and html_attr strategies (K…
Browse files Browse the repository at this point in the history
…ocal)

This PR was merged into the 3.x branch.

Discussion
----------

[Doc] Document about `html` and `html_attr` strategies

Ref #4322

Commits
-------

ac88c9a [Doc] Document about `html` and `html_attr` strategies
  • Loading branch information
fabpot committed Sep 21, 2024
2 parents 9e1b544 + ac88c9a commit 3f03d2b
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions doc/filters/escape.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ And here is how to escape variables included in JavaScript code:
The ``escape`` filter supports the following escaping strategies for HTML
documents:

* ``html``: escapes a string for the **HTML body** context.
* ``html``: escapes a string for the **HTML body** context,
or for HTML attributes values **inside quotes**.

* ``js``: escapes a string for the **JavaScript** context.

Expand All @@ -50,7 +51,8 @@ documents:
* ``url``: escapes a string for the **URI or parameter** contexts. This should
not be used to escape an entire URI; only a subcomponent being inserted.

* ``html_attr``: escapes a string for the **HTML attribute** context.
* ``html_attr``: escapes a string for the **HTML attribute** context,
**without quotes** around HTML attribute values.

Note that doing contextual escaping in HTML documents is hard and choosing the
right escaping strategy depends on a lot of factors. Please, read related
Expand Down Expand Up @@ -90,6 +92,27 @@ to learn more about this topic.
{{ var|escape(strategy)|raw }} {# won't be double-escaped #}
{% endautoescape %}
.. tip::

The ``html_attr`` escaping strategy can be useful when you need to
escape a **dynamic HTML attribute name**:

.. code-block:: html+twig

<p {{ your_html_attr|e('html_attr') }}="attribute value">

It can also be used for escaping a **dynamic HTML attribute value**
if it is not quoted, but this is **less performant**.
Instead, it is recommended to quote the HTML attribute value and use
the ``html`` escaping strategy:

.. code-block:: html+twig

<p data-content="{{ content|e('html') }}">

{# is equivalent to, but is less performant #}
<p data-content={{ content|e('html_attr') }}>

Custom Escapers
---------------

Expand Down

0 comments on commit 3f03d2b

Please sign in to comment.