1252748
1252748

Reputation: 15372

How to use microtemplate

For some reason, I can't get the John Resig micro template to work. I've read here, and can get this example to work, but it is for a very simple object.(ie. var data = { fname : "fred" };), however, when I try to use my more complicated object

{"order":{"name":"TRADEMARK WHEEL COMPANY","sales_order_id":"18278","order_date":"05 \u2044 15 \u2044 2012","due_date":"05 \u2044 21 \u2044 2012","order_number":"1213140","reference":"21192D\/35546","order_description":"BICICLETTE","ship_name":"ADAMS","ship_address1":"1919 W RANDOLPH ST.","ship_address2":"","ship_city":"CHICAGO","ship_state":"IL","ship_postal_code":"60606","ship_country":null,"ship_via":"FEDEX GROUND","tracking_number":null,"package_contents":null,"freight":"0.00","taxable":"0.00","nontaxable":"748.88","sales_tax":"0.00"},"line_item":[{"description":"RED ONE","quantity":"2.00","sell_price":"349.44"},{"description":"FRONT GEAR","quantity":"2.00","sell_price":"15.00"},{"description":"5th GEAR","quantity":"2.00","sell_price":"10.00"}]}

and try to access it like so

<script>
(function () {

  var submitStr="test string of data";

  $.ajax({
    type: "POST",
    url: "getJSON.php",
    data: submitStr,
    success: function (data) {
    console.log(data);
    var generatedText = tmpl("order_detail", data);
    var elem = document.getElementById("elemId");
    elem.innerHTML = generatedText;
    }
    });

}());
</script>
<script id="order_detail" type="text/html">
        <div>
Name:<%=data.order.name%> ID:<%=data.order.sales_order_id%><hr/>

<%for(var i=0;i<data.line_item.length;i++) {%>

      description: <%= data.line_item[i].description %><br/>
      quantity: <%= data.line_item[i].quantity %><br/>
      price: <%= data.line_item[i].sell_price %><hr/>


<%}%>
</div> 

 </script> 

I get the error that data is undefined. I've tried it without data., simply trying to access the object's values directly, but that doesn't work either.

I'm grateful for any help using this thing!

Upvotes: 0

Views: 1285

Answers (1)

wong2
wong2

Reputation: 35740

1.In $.ajax success callback success: function (data) you get the data as a JSON string, you have to parse it to an object before pass it to the tmpl function.

$.ajax({
    type: "POST",
    url: "getJSON.php",
    data: submitStr,
    success: function (data) {
        console.log(data);

        data = JSON.parse(data);

        var generatedText = tmpl("order_detail", data);
        var elem = document.getElementById("elemId");
        elem.innerHTML = generatedText;
    }
});

2.remove all the data prefix in your template.

Upvotes: 1

Related Questions