Search code examples
javascriptjquerytemplatesmustache

Modify html before it gets templated


I am using Mustache template script to render my JSON values. I was wondering : Since I need to bind data to the html I'm rendering , there is a way to apply .data() to the object I'm going to render?

I explain it better with some code :

var temp = $("#template").html(),
     obj = Mustache.render(temp,this);
  //I want to bind data to obj before it gets appended
  $('#appended').append(obj);

Solution

  • Modify obj before or after you append it.

    var temp = $("#template").html(),
        obj = Mustache.render(temp,this);
    
    $(obj).data("foo","bar").appendTo('#appended');
    

    or

    var temp = $("#template").html(),
        $obj = $(Mustache.render(temp,this));
    
    $('#appended').append($obj)
    $obj.data("foo","bar");
    

    If your html doesn't start with a tag, you'll have to parse it first.

    var temp = $("#template").html(),
        $obj = $( $.parseHTML( Mustache.render(temp,this) ) );
    
    $('#appended').append($obj)
    $obj.data("foo","bar");