2014-02-16 24 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