问题
Given
<div id="place_holder" />
<script id="template" type="text/x-jquery-tmpl">
WHAT DO I PUT HERE
</script>
var array_of_ints = [1,2,3]
$( "#template" )
.tmpl( array_of_ints )
.appendTo( "#place_holder" );
What can I put within the template to get ?
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
回答1:
<ul id="place_holder">
</ul>
<script id="template" type="text/x-jquery-tmpl">
<li>${}</li>
</script>
var array_of_ints = [1,2,3]
$("#template")
.tmpl(array_of_ints)
.appendTo( "#place_holder" );
回答2:
<div id="place_holder" />
<script id="template" type="text/x-jquery-tmpl">
{{= $data}}
</script>
var array_of_ints = [1,2,3]
$( "#template" )
.tmpl( array_of_ints )
.appendTo( "#place_holder" );
{{= $data}} works everywhere ( ${} wont work in strings in the template )
回答3:
${} didn't work for me with an array of strings ['A String','Another String','Yet Another String'] , but {{= $data}} does. thanks!
回答4:
You want to look into the {{each}} template tag.
In this case, I don't think that jQuery.tmpl is really the best way to do this. It would be much easier in my opinion just to use a standard for
loop.
var array_of_ints = [1,2,3];
//creates the ul
var ul = $('<ul></ul>');
//creates the LI's
for(var i = 0; i < array_of_ints.length; i++){
ul.append('<li>' + array_of_ints[i] + '</li>');
}
//adds to the placeholder
$('#placeholder').append(ul);
http://jsfiddle.net/LeKYu/
来源:https://stackoverflow.com/questions/6105943/can-jquery-template-bind-to-a-raw-array