1

I want to get array using underscore.js.

Here is my case.

view.js

views.list = Backbone.View.extend({
      render: function(templateName) {
        var template = _.template(templateName);
        this.$el.html(template({result : this.collection.models}));
        _.each(this.collection.models, function(model){
          console.log(model.get("id"));
        });
        return this;
      }
    });

Run result _.each(this.collection.models, function(model){console.log(model.get("id"));});

enter image description here

list.html

<div id="columns">
      <% _.each(result, function(model){ %>
        <div id="<% model.get("id") %>" class="content">
          <a href="<% model.get("url") %>">
            <figure>
              <img src="<% model.get("imgSrc") %>">
              <figcaption><% model.get("title") %></figcaption>
            </figure>
        </div>
      <% }); %>
      </div>

enter image description here

I sent an argument to this.collection.model as result parameter, so I think the above executable code and the executable code I wrote in html are the same, but the running result is not the same.

What's the difference?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Liquid.Bear
  • 333
  • 6
  • 21
  • 1
    Instead of executing `var template = _.template(templateName);` every time render is called, store the template function as a `template` property of view – T J Feb 27 '17 at 21:21
  • @TJ ok thanks :) i knew one more today – Liquid.Bear Mar 07 '17 at 13:55

1 Answers1

2

You need to use expressions in the template which output a value. Instead of

<div id="<% model.get("id") %>" class="content">

You need:

<div id="<%- model.get("id") %>" class="content">

See the docs

mikeapr4
  • 2,830
  • 16
  • 24