如何在Underscore模板中存储JSON数据?

时间:2013-05-21 14:58:38

标签: javascript jquery json templates underscore.js

我想在Underscore模板中存储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>

如果我将“options”作为JSON字符串或JSON对象传递,则上述操作无效。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

诀窍是在处理容纳JSON数据的html5数据属性时使用单引号:

<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>

请注意,单引号用于保存数据选项的值而不是双引号。

答案 1 :(得分:0)

您可以尝试传递

{options: JSON.stringify(options)} 

到模板:)之后你需要在阅读时解析它。