2014-02-16 23 views
4

我想写一个构建在Express上的行程应用程序。 Swig是模板引擎。我对Swig的autoescape功能感到困惑。它究竟做了什么?什么是用于Node.js的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> 

谢谢。

回答

9

文件应该这样写:

"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 }}; 
... 
+1

谢谢,这是有道理的。 – user2954463

+1

我一直在寻找小时如何防止swig做到这一点。谢谢!! – Radioreve