【问题标题】:How to render a JS object with underscore templates?如何使用下划线模板渲染 JS 对象?
【发布时间】:2017-03-15 05:16:30
【问题描述】:

我正在尝试使用下划线模板和 Backbone.js 呈现 JS 数据对象。

我创建了如下图所示的数据。

然后,我看到了类似的问题。
How to display a JS object with underscore templates?

我不知道 Backbone.js 集合和模型是否正确,但最近我了解了这些。
我已经将数据插入到如下源代码中的集合中。

//that's create view
wordCollection.add(wordList);
var view = new views.Livingword({collection:wordList});

//that's view 
render: function(templateName) {
        var template = _.template(templateName);
        this.$el.html(template({result : this.collection.category}));
        return this;
      }

然后,我写了html源代码。

  <% _.each(result, function(item,key,list){ %>
            <tr>
            <td><%- category[key].bedroom %></td>
            </tr>
          <% }) %>

但是,打印错误Uncaught ReferenceError: category is not defined
所以我尝试在运行时调试由控制台命令产生的collection console.log(this.collection.category); 如下图。

我认为创建数据是合适的,不要找到错误的源代码。
如何在 html 中呈现我的数据?

【问题讨论】:

  • 您将this.collection.category 作为result 传递给模板。所以,你应该使用result[key].. 而不是category[key]..,对吗? category 在模板范围内应该是 undefined
  • 天哪.. 真的谢谢
  • @RaR hmm.. 错误已处理,但没有显示任何内容.. 我输入 &lt;%- result[key].audioSrc %&gt; 有什么问题?

标签: javascript templates backbone.js underscore.js underscore.js-templating


【解决方案1】:

在每次迭代中,您代码中的item 将是诸如“卧室”之类的值,它们是包含对象的数组。
因此,为了遍历并打印其中的每个项目,您需要再次迭代。

<% _.each(result, function(arr, key, list){ %>
 <!-- Add <tbody>, <thead> etc with "key" here -->

  <% _.each(arr, function(item, key, list){ %>
     <tr>
        <td><%= item.audioSrc %></td>
     </tr>
  <% }) %>

<% }) %>

现在在上面的代码中,audioSrc 是硬编码的。如果您知道要打印的所有属性,则可以这样做。如果你不这样做(它们是动态的),那么你需要另一个迭代来遍历 item 的每个属性。

旁注:

  • 不要在每次渲染时执行var template = _.template(templateName);,而是执行

    template: _.template(templateName), // one time
    render: function(templateName) { 
        this.$el.html(this.template({result: this.collection.category}));
        return this;
    }
    
  • 为传递给模板的内容赋予有意义的名称。 result 是一个模糊的名称。 category 更好,但它是一个类别图,正确的命名应该是 categories。所以this.template({categories: this.collection.category}。如果名称很清楚,您在编写模板时会更好地了解自己在做什么

  • 根据用法:this.collection.category,我很确定它应该是模型而不是集合。集合用于一组事物,您将使用它的模型数组,例如 this.collection.models
    因此,随着所有更改,您的代码应该类似于

    template: _.template(templateName), // one time
    render: function(templateName) { 
        this.$el.html(this.template({categories: this.model.categories});
        // ---- This can be an Array or Collection instance -----^
        return this;
    }
    

    带模板:

    <% _.each(categories, function(category, name){ %>
    <!-- Add <tbody>, <thead> etc with "name" here -->
    
      <% _.each(category, function(item, name){ %>
        <tr>
          <td><%= item.audioSrc %></td>
        </tr>
      <% }) %>
    
    <% }) %>
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多