[简单]Handlebars简单例子

       Handlebars官网链接:http://handlebarsjs.com/,下面是一个简单的例子,欢迎吐槽.

      

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Handlebars Expressions Example</title>
<script type="text/javascript" src="../js/jquery-2.1.0.js"></script>
<script type="text/javascript" src="../js/handlebars-v1.3.0.js"></script>
<script id="people-template" type="text/x-handlebars-template">
       {{#each people}}
        <div>
          <div>{{diyName first_name last_name email}}</div>
          <div>{{isHasPhone phone}}</div>
          <div><a href="mailto:{{email}}">{{email}}</a></div>
          <div>User since: {{member_since}}</div><br/>
        </div>
      {{/each}}
    </script>

<script type="text/javascript">
	$(document).ready(function() {
		Handlebars.registerHelper("isHasPhone", function(txt,fn) {
			var strVar = "";
			if($.trim(txt)!=''&&$.trim(txt)!='NULL'){
				strVar = '<span>联系电话:'+txt+'</span>';
			}else {
				strVar = '<span>暂无联系方式</span>';
			}
			return new Handlebars.SafeString(strVar);
		});
		Handlebars.registerHelper("diyName", function(var1,var2,var3,fn) {
			var strVar = "";
			if($.trim(var3)==''){
				strVar = '<span>'+var1+' '+var2+'</span>';
			}else{
				strVar = '<a href="mailto:'+var3+'">'+var1+' '+var2+'</a>';
			}
			return new Handlebars.SafeString(strVar);
		});
		// compile our template
		var template = Handlebars.compile($("#people-template").html());
		var data = {
			people : [ {
				first_name : "中文",
				last_name : "测试",
				phone : "1234567890",
				email : "[email protected]",
				member_since : "2014-4-11"
			}, {
				first_name : "Allison",
				last_name : "House",
				phone : " ",
				email : "[email protected]",
				member_since : "2014-5-12"
			} , {
				first_name : "测试",
				last_name : "House",
				phone : "NULL",
				email : "[email protected]",
				member_since : "2014-6-11"
			}, {
				first_name : "无链接",
				last_name : "test",
				phone : "NULL",
				email : " ",
				member_since : "2014-6-1"
			} ]
		};
		$('#test').html(template(data));
	});
</script>
</head>
<body>
	<h1>Handlebars Expressions Example!</h1>
	<!--this is a list which will rendered by handlebars template.    -->
	<div id="test"></div>
</body>
</html>

    结果为

   
[简单]Handlebars简单例子
      全文完

 

你可能感兴趣的:(单例)