如何在下划线模板中存储JSON数据

How do I store JSON data in an Underscore template?

本文关键字:存储 JSON 数据 下划线      更新时间:2023-09-26

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

如果我将"选项"作为JSON字符串或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>

注意这里的单引号用来保存data-options的值,而不是双引号。

您可以尝试传递

{options: JSON.stringify(options)}