javascript - Data not appending to element in Handlebars.js -
<!doctype html> <html> <head> <meta charset=utf-8 /> <title>js bin</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js" type="text/javascript" charset="utf-8"></script> <script src="app.js" type="text/javascript" charset="utf-8"></script> </head> <body> <ul> <script id ="ajaxtemplate" type="text/x-handlebars-template"> {{#each}} <li> <span class="meta">{{name}} on {{date}}</span> <p>{{comment}}</p> </li> {{/each}} </script> </ul> <script> $(document).ready(function(){ //document.write("hello"); var data = [{ "name":"name2", "date":"12/12/1999" }, { "name":"name1", "date":"12/12/1999" }] var source = $.trim($('#ajaxtemplate').html()); var template = handlebars.compile(source); var html = template(data); //document.write(html); $('ul').append(html); }); </script> </body> </html>
can tell me mistake in above code. not able append compiled js code dom.
the below 1 works perfectly, see change code. {{#each data}}
references data.data
, expects array
loop through.
<!doctype html> <html> <head> <meta charset=utf-8 /> <title>js bin</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js" type="text/javascript" charset="utf-8"></script> </head> <body> <ul> <script id ="ajaxtemplate" type="text/x-handlebars-template"> {{#each data}} <li> <span class="meta">{{this.name}} on {{this.date}}</span> </li> {{/each}} </script> </ul> <script> $(document).ready(function(){ //document.write("hello"); var data = {data:[{ "name":"vinoth", "date":"12/12/1984" }, { "name":"kevin", "date":"7/23/1984" }]}; var source = $.trim($('#ajaxtemplate').html()); var template = handlebars.compile(source); var html = template(data); //document.write(html); $('ul').append(html); }); </script> </body> </html>
working example: http://jsbin.com/ecazege/1
also can use {{#each this}}
, don't need alter data @ on did. using this
more readable way.
below fiddle using this
. http://jsbin.com/ecazege/6
Comments
Post a Comment