开发者

Jquery template isn't working with 'each'

My source code is here:

http://jsfiddle.net/2pkHL/

I can't figure out why it doesn't render correctly. Also, is there a way without nesting the data inside another object?

<script id='myTemplate' type='text/x-jquery-tmpl'>

Table of stuffs:

<table>
{{each value}}
<tr>
    <td>${name}</td>
    <td>${value}</td>
</tr>
{{/each}}

</table>


</script>


<div id="target">

</div>



var something = function () { };

var results = [{ name: 'First', value: 1 }, { name: 'Second', value: 2 }];

something.value = results;

$('#myTemplate').tmpl(something).ap开发者_如何学CpendTo('#target');


You only need these two lines:

var results = [{ name: 'First', value: 1 }, { name: 'Second', value: 2 }];
$('#myTemplate').tmpl({value: results}).appendTo('#target');

I'm using a plain object instead of a function. See demo: http://jsfiddle.net/2pkHL/6/.


You can make things even simpler. Since only the rows are affected by the data (not the <table>), you can include only rows in the template, supply an array directly as the data, and tmpl will automatically generate the HTML for each element in the array:

<script id='myTemplate' type='text/x-jquery-tmpl'>
<tr>
    <td>${name}</td>
    <td>${value}</td>
</tr>
</script>

Table of stuffs:
<table id="target">
</table>

Js:

var results = [{ name: 'First', value: 1 }, { name: 'Second', value: 2 }];
$('#myTemplate').tmpl(results).appendTo('#target');

See this version here: http://jsfiddle.net/2pkHL/11/


Well, your main problem is that you say that var something is a function. If you make it an object, you're set to go! :)

Here is an updated fiddle; http://jsfiddle.net/2pkHL/5/

And of course the updated vode in here too:

<script id='myTemplate' type='text/x-jquery-tmpl'>
Table of stuffs:
<table>
{{each value}}
<tr>
    <td>${name}</td>
    <td>${value}</td>
</tr>
{{/each}}
</table>
</script>
<div id="target">
</div>

And the JS:

var something = {};

var results = [{ name: 'First', value: 1 }, { name: 'Second', value: 2 }];

something.value = results;

$('#myTemplate').tmpl(something).appendTo('#target');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜