Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is auto escape used for in Swig templating for Node.js?

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.

like image 858
user2954463 Avatar asked Dec 26 '22 13:12

user2954463


1 Answers

The documentation should read like this:

"Control auto-escaping of variable output from within your templates."

// myvar = '<foo>';
{% autoescape true %}{{ myvar }}{% endautoescape %}
// => &lt;foo&gt;
{% 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 }};
...
like image 158
robertklep Avatar answered Dec 28 '22 11:12

robertklep