Handlebars 的使用

阅读更多
web 开发中,js 解析JSON 是经常的事情。非常繁琐。handlebars 使用了模版,只要你定义一个模版,提供一个json对象,handlebars 就能吧json对象放到你定的模版中,非常方便好用! 下面直接上代码:





Handlebars demo






	

Simple handlebars demo

Handlebars Helpers demo



$(document).ready(function(){
	Handlebars.registerHelper('fullName', function(person) {
	  return person.firstName + " " + person.lastName;
	});
  $("#btn_simple").click(function(){
    // $(this).hide();
    showTemplate();
  });
   $("#btn_helper").click(function(){

    showHowUseHelper();
  });
});
// var context = {title: "My New Post", body: "This is my first post!"};
var persion = {title :"My New Post",body:"This is my first post!"}
function showTemplate(){
	var source   = $("#some-template").html();
  	var template = Handlebars.compile(source);
	  var data = { users: [
	      {username: "alan", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
	      {username: "allison", firstName: "Allison", lastName: "House", email: "[email protected]" },
	      {username: "ryan", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
	    ]};
	  $("#my_div").html(template(data));;
}

function showHowUseHelper(){
	var context = {
	  author: {firstName: "Alan", lastName: "Johnson"},
	  body: "I Love Handlebars",
	  comments: [{
	    author: {firstName: "Yehuda", lastName: "Katz"},
	    body: "Me too!"
	  }]
	};
	var source   = $("#helper-template").html();
  	var template = Handlebars.compile(source);
	$("#helper_div").html(template(context));;
	
}

你可能感兴趣的:(html,js,javascript,jquery,web)