Call html() function on $.tmpl function's return object

Plunker code is here.

I am trying to get the html content out of a jquery template and its data. Is n't the return type of tmpl a jquery wrapped object?

This code,

$.each($('#movieTemplate').tmpl(movies), function(idx,elt){
  tmplContent = tmplContent + elt.html()
  });

throws error as

elt.html is not a function

Note: I can make it work with an alternate way as shown in plunker

But i am trying to figure out the object type of $.tmpl's return value?

Answers 1

  • Use document.createElement to create an html container and instead of concatenating the html as string, append the html

    var movies = [
        { Name: "The Red Violin", ReleaseYear: "1998" },
        { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
        { Name: "The Inheritance", ReleaseYear: "1976" }
    ]
    
    var tmplContent = $("<div />").append($.tmpl('  <li>    <b>${Name}</b> (${ReleaseYear})  </li>', movies)).html()
    $('#results-0').html(tmplContent)
    
    var tmplContent = document.createElement('div');
    $.each($('#movieTemplate').tmpl(movies), function(idx,elt){
        tmplContent.appendChild(elt);
        //tmplContent = tmplContent + elt.toString()
    });
    
    $('#results-1').html(tmplContent)
    

    Or if you still want to use it as string, you can do it this way

    $.each($('#movieTemplate').tmpl(movies), function(idx,elt){
        tmplContent = tmplContent + $(elt).prop('outerHTML');
    });
    

Related Articles