在Node.js的Swig模板中使用的自动转义是什么?

时间:2014-02-16 02:06:30

标签: node.js express swig-template

我正在尝试编写一个基于Express构建的行程应用程序。 Swig是模板引擎。我对Swig的自动景观功能感到困惑。它到底是做什么的?

Swig documentation示例:

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

// myvar = '<foo>';
{% autoescape true %}{{ myvar }}{% endautoescape %}
// => <foo>
{% autoescape false %}{{ myvar }}{% endautoescape %}
// => <foo>

我的代码:

<script>

{% autoescape false %}
var all_hotels = {{ hotels | json }};
var all_restaurants = {{ restaurants | json }};
var all_things_to_do = {{ things_to_do | json }};

{% endautoescape %}

</script>

谢谢。

1 个答案:

答案 0 :(得分:10)

文档应如下所示:

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

// myvar = '<foo>';
{% autoescape true %}{{ myvar }}{% endautoescape %}
// => &lt;foo&gt;
{% autoescape false %}{{ myvar }}{% endautoescape %}
// => <foo>

因此,当autoescape为true时,它将HTML转义变量内容。我认为这是Swig的默认设置。

由于您要呈现JSON变量,因此您的代码应该可以正常工作(关闭自动转换以防止HTML转义JSON内容)。或者,您可以使用safe过滤器:

var all_hotels = {{ hotels | safe | json }};
var all_restaurants = {{ restaurants | safe | json }};
...