【问题标题】:How do I store JSON data in an Underscore template?如何在下划线模板中存储 JSON 数据?
【发布时间】:2013-05-21 14:58:37
【问题描述】:

我想在下划线模板中存储一个 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 对象传递,上述方法将不起作用。有什么想法吗?

【问题讨论】:

  • 我会确保您的选项中没有任何双引号。您可能还需要使用

标签: javascript jquery json templates underscore.js


【解决方案1】:

诀窍是在处理包含 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>

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

【讨论】:

    【解决方案2】:

    你可以尝试通过

    {options: JSON.stringify(options)} 
    

    到模板 :) 之后,您需要在阅读时将其解析回来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      相关资源
      最近更新 更多