0
votes

I am using backbone.js and the underscore template system to dynamically display data from a json file. My template is not working when I console log in the html with <%console.log('template test') %> What am I doing wrong when trying to work with underscores template? Also how can I loop through the json file and grab the "price" and display it with the template?

If the question is not clear I will try to explain more. Any help is appreciated, Thanks!

A sample of the json file that looks like this

//addToCartResponce.json//

  {    
 "response":{
    "headers":{
       "store":"123",
        "id":"321"
     },
     "cart":{
        "message":"na",
       "orderId":"333",
        "orderItems":{
           "orderItem":[
               {
                "price":"$1.00",
                 "qty":"1",
                  "methods":{
                     "selectedMethod":{
                        "SelectedFFMCenter":"DDC",
                        "SelectedStore":"na"
                     }
                  }
               }
            ]
         }
      }
   }
}

Here is my backbone files.

Collection

var cartCollection = Backbone.Collection.extend({
      el: this,
      url: function() {
          return window.location.href + '/assets/js/ajax/addToCartResponce.json'
       },
       parse: function(resp) {
           return resp.response;
       },
          initialize: function() {
                  this.fetch({
                    async: false
                   });

                  this.on('add',this.cartFunction());
                  var shoppingCart = this.pluck('cart'); 
                  console.log("this.pluck('cart')");
                  console.log(shoppingCart);

         }, // end of initialize

        cartFunction: function(){
           console.log('cart Functon');

        }


});  // The console logs in cartCollection are working.

View

cartContent = Backbone.View.extend({
            el: $('.cartContent'),
            initialize: function() {
               this.render();
         },

         render: function( ){
           this.collection = new cartCollection();
           var cart_template = _.template( $(".cartContentTemplate").html() ); 
           this.$el.html( cart_template );

               return this; 
              }
 });

   cartView = new cartContent();

HTML

<script type="text/template" class ="cartContentTemplate">  
    <div class="cartContent">
      <% console.log('template test'); %>
    </div>
</script>   
1

1 Answers

2
votes

_.template returns a function. You need to pass the needed data (or nothing) to that function to get back the populated html. Re-write render as

render: function () {
    this.collection = new cartCollection();
    var cart_template = _.template( $(".cartContentTemplate").html() ),
        html = cart_template();

    this.$el.html(html);

    return this; 
}

How to display the price?

You can read more about writing underscore templates as these two links:

http://www.bennadel.com/blog/2411-Using-Underscore-js-Templates-To-Render-HTML-Partials.htm

How to use underscore.js as a template engine?

To answer your question,

<script type="text/template" id="cartContentTemplate">  
    <div class="cartContent">
      <% if (cart && cart.orderItems) { 
            _.each(cart.orderItems.orderItem, function (item) { %>

             <div> Price: <%- item.price %> </div>

      <% });
      } %>
    </div>
</script>   

Another observation, you are fetching the template script using the class selector. Script tags were not meant to have the class attribute. It's not valid html. While it may work currently in some browser, it can just as easily not work in some other browser currently or in future. You should be using the id selector instead. Rewrite your template as follows:

<script type="text/template" id="cartContentTemplate">  
    <div class="cartContent">
      <% console.log('template test'); %>
    </div>
</script>   

and read-in the template using

var cart_template = _.template($("#cartContentTemplate").html());