2013-05-21 57 views
1

我想將一個JSON對象或字符串存儲在Underscore模板中。如何將JSON數據存儲在Underscore模板中?

<script id="report_field_template" type="text/template"> 
    <div data-options="<%= options %>" role="<%- role %>" title="<%- title %>" class="ui-widget-content ui-corner-all report_field"> 
     <p><%- field_text %></p> 
    </div> 
</script> 

如果我將「options」作爲JSON字符串或JSON對象傳遞,上述方法將不起作用。有任何想法嗎?

+1

我會確保你的選項中沒有任何雙引號。您可能還需要使用<% - 來轉義選項。 – bottens

回答

3

訣竅是用HTML5數據 - 打交道時屬性那家JSON數據使用單引號:

<script id="report_field_template" type="text/template"> 
    <div data-options='<%= options %>' role="<%- role %>" title="<%- title %>" class="ui-widget-content ui-corner-all report_field"> 
     <p><%- field_text %></p> 
    </div> 
</script> 

注意單引號用來保存數據的選項,而不是雙引號的值。

0

您可能會嘗試通過

{options: JSON.stringify(options)} 

到模板:)後,你需要分析它的背部,同時閱讀。

相關問題