7

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>

4 Answers4

8
<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 )

nidx
  • 91
  • 4
  • What do you mean by ${} wont work in strings in the template? Can you give an example where {{= $data}} works but ${} doesn't? –  Jul 28 '11 at 06:24
  • setting tag attributes like name and src – nidx Sep 02 '11 at 17:53
4
<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" );
Dave
  • 2,409
  • 3
  • 22
  • 28
1

${} didn't work for me with an array of strings ['A String','Another String','Yet Another String'] , but {{= $data}} does. thanks!

Mike
  • 51
  • 1
  • 8
-1

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/

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
  • The question was asking whether it can be done using jQuery.tmpl –  May 26 '11 at 00:44
  • @Michael Wolfenden: I understand that, which is why I posted the link to the `{{each}}` template tag. I would recommend changing your example, because using jQuery.tmpl for this is completely pointless. A more realistic example would better serve you and any future readers. – Alastair Pitts May 26 '11 at 01:36
  • @Michael Wolfdenden: I'm also fairly sure there is no way for you to get access to the root object. What it's doing is for each object/value in the array, it's calling the template, rather than calling the template with the array. – Alastair Pitts May 26 '11 at 01:46