I'm using the Twig templating system as well as the Timber plugin within WordPress and one thing the Timber pages say about escaping is that:
By default, Timber does not escape the output of standard tags (i.e. {{ post.field }}). If you want to enable autoescape behavior simply add these lines to functions.php:
https://timber.github.io/docs/guides/escapers/
Does this mean if I turn this on I won't need to do any escaping whatsoever? Not for the html body, attributes, url's etc?
Additionally, if I don't turn this on, does this mean it is recommended do do something like this:
<nav role="navigation">
<ul class="main-nav">
{% for item in menu.get_items %}
<li class="{{ fn('esc_attr', (item.classes | join(' '))) }}">
<a href="{{ item.get_link|e('esc_url') }}">{{ item.title|e }}</a>
{% if item.children %}
<ul class="sub-menu">
{% for child in item.children %}
<li class="sub-menu-item">
<a href="{{ child.get_link|e('esc_url') }}">{{ child.title|e }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
</ul>
</nav>
I used fn('esc_attr', item.classes)
to utilise the WordPress escaper esc_attr
as it doesn't appear like Timber has an escape for attributes and the Twig version wasn't added to 1.9, but it appears Timber is on 1.35.2.
Are there any disadvantages to auto-escaping? Doesn't seem to me like there would be unless you were planning on not escaping everything? ...and you can always utilise |raw
if you don't want something escaped I would assume?
Are there any disadvantages to auto-escaping?
No. It is recommended (and the default functionality) as outputting raw should be something the developer thinks about at development time and not an after thought.
Lets say you have this: <h1>{{ variable }}</h1>
here is a table of what this would look like:
| Auto Escape | Default Functionality |
| ----------- | --------------------- |
| Disabled | {{ variable|raw }} |
| Enabled | {{ variable|e }} |
In twig we have these filters |raw
and |escape
(or |e
).
Does this mean if I turn this on I won't need to do any escaping whatsoever? Not for the html body, attributes, url's etc?
I cannot say for sure but I am also going to say no. I believe what it means by auto escaping is simply what I mentioned above. It will not automatically select an escaping strategy (so it won't know when to use |e('html')
) but instead run everything through the standard |e
unless manually ran through |e('html')
or |raw
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With