I'm trying to write an itinerary app built on Express. Swig is the template engine. I'm confused by Swig's autoescape feature. What exactly does it do?
Swig documentation example:
"Control auto-escaping of variable output from within your templates."
// myvar = '<foo>';
{% autoescape true %}{{ myvar }}{% endautoescape %}
// => <foo>
{% autoescape false %}{{ myvar }}{% endautoescape %}
// => <foo>
My code:
<script>
{% autoescape false %}
var all_hotels = {{ hotels | json }};
var all_restaurants = {{ restaurants | json }};
var all_things_to_do = {{ things_to_do | json }};
{% endautoescape %}
</script>
Thank you.
The documentation should read like this:
"Control auto-escaping of variable output from within your templates."
// myvar = '<foo>';
{% autoescape true %}{{ myvar }}{% endautoescape %}
// => <foo>
{% autoescape false %}{{ myvar }}{% endautoescape %}
// => <foo>
So when autoescape is true
, it will HTML-escape variable content. I think this is the default setting for Swig.
Since you want to render JSON-variables, your code should work okay (turning off autoescaping to prevent HTML-escaping of the JSON content). Alternatively, you could use the safe
filter:
var all_hotels = {{ hotels | safe | json }};
var all_restaurants = {{ restaurants | safe | json }};
...
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