Leahcim
Leahcim

Reputation: 41919

Backbone: mixing html and javascript in template

In this "hello world" example of a Backbone app http://arturadib.com/hello-backbonejs/docs/5.html, the author renders a template inline like this

render: function(){
      $(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> &nbsp; &nbsp; <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
      return this; // for chainable calls, like .render().el
    },

which, although functional, is a bit of an unmanageable html concatenation.

I've seen authors of other Backbone apps set a template in the view using underscore's template function

template: _.template($('#my-template').html()),

and then render it instead of the html

$(this.el).html(this.template(this.model.toJSON()));

I wanted to try this technique with the hello world app, but when I created the template file, I ran into the problem that it wasn't strictly html. As you'll notice it calls functions

 this.model.get('part2')

and the template that I was using as a model (from another author's app, see below) just included html.

Question, What would I need to do to include javascript and html in the same template file so I can make a call to the model?

<script type="text/template" id="item-template">
      <div class="company">
        <div class="display">
          <span class="company-text"></span>
          <span class="company-mood">
            <span class="mood"></span>
          </span>
          <span class="company-destroy"></span>
        </div>
        <div class="edit">
          <input class="company-input" type="text" value="" />
        </div>
      </div>
    </script>

Upvotes: 0

Views: 382

Answers (1)

jmk2142
jmk2142

Reputation: 8581

See this link Underscore Template for details on what you want to accomplish.

But in general, if you just wanted to interpolate your this.model.get('someAttr'); all you'd need to do is include this in your template.

// Since you call it like this:
$(this.el).html(this.template(this.model.toJSON()));

// Just include this
<div>
    <%= someAttr %>
</div>

You're basically passing in the model attributes object and the underscore template just interpolates the properties of that object. You can pass in anything you want although what you do with the render call is what's probably most common.

Upvotes: 2

Related Questions