pyccki
pyccki

Reputation: 693

jQuery template/tmpl how to build dynamic output from json?

Trying to build dynamic output from json and using jq/template tmpl display rows/columns. Somehow i need to iterate thru columns and Rows not sure how.

I do NOT KNOW name of json properties, so it needs to be dynamic.

Finally got an answer Here

<script id="template" type="text/x-jquery-tmpl">
        <li>{Need Loop here?}</li>           
 </script>

var invoice = {
  invoiceItems: [
    { type: 'item', 
      part: '99Designs', description: '99 Designs Logo', 
      price: 450.00, qty: 1 },
    { type: 'service',
      service: 'Web development and testing', 
      price: 25000.00 },
    { type: 'item',
      part: 'LinodeMonthly', description: 'Monthly site hosting', 
      price: 40.00, qty: 12 }
  ]
};

$("#template")
    .tmpl(invoice.invoiceItems)
    .appendTo("#place_holder");

Also, is any way to display json property name? Like:

type > part > description> .....

Here's jsFiddle

Update:

I start using Jsrender, much faster. I still haven't figure out how to create dynamic templates. Will update if get completed.

Upvotes: 0

Views: 3684

Answers (4)

Roland
Roland

Reputation: 9701

I would go for : Angular.

You get more than just template rendering ( you can also make your templates more dynamic ) but you also get a two way data binding which in most cases is very welcomed.

Upvotes: 0

pyccki
pyccki

Reputation: 693

Finally got a help from Friend of mine.

Template

<script id="template" type="text/x-jquery-tmpl">
{{each(i, invoiceItem) invoiceItems}}
    <li>
    {{each(j, property) $item.getProperties(invoiceItem) }}
       ${invoiceItem[property]} >>
    {{/each}}
    </li>
{{/each}}
</script>

Helper function

var functionHelpers = {
getProperties: function(invoiceItem) {
    var properties = [];

    for(var key in invoiceItem) {
        properties.push(key);
    }

    return properties;
}

};

Here's working example jsFiddle

Upvotes: 2

Jesse
Jesse

Reputation: 5074

I'm not sure why you think you need to loop, jquery.tmpl is doing the looping for you. You just need to use ${} to output the data in the markup you want: jsfiddle.

Upvotes: 0

Related Questions