文章来自net|tuts+ 原文地址 请点击
<h1>Welcome back, {{name}}</h1>
{{name}}
属性是用户名称是动态注入到页面里来的. 这个占位符是使用一种类似Json结构, 这可能是最基本的例子, 但是你将看到的每一个都会基于这个简单的理念. 让我们继续看这个 "数组".
你能看到, 这段代码比常规的代码要清晰很多, 类似使用 PHP的loop/Javascript的动态append页面. Handlebars的语法不具有 "intrusive"干扰性, 所以它是很容易理解的. 你可能不会注意到 {{this}} 意思是取出loop中当前的 element。<table><tr><th>Local Concerts</th></tr>
{{#each Concerts}}<tr><td>{{this}}</td></tr>
{{/each}}</table>
[
{
Name : "Band",
Date : "Aug 14th, 2012",
Albums : [
{
Name : "Generic Name"
},
{
Name : "Something Else!!"
}
]
},
{
Name : "Other Guys",
Date : "Aug 22nd, 2012"
Albums : [
{
Name : "Album One"
}
]
}
]
我们很容易使用下面的template来实现上面的数据显示:
<table><tr><th>Band Name</th><th>Date</th><th>Album Name</th></tr>{{#each Bands}}<tr><td>{{Name}}</td><td>{{Date}}</td><td>{{Albums.0.Name}}</td></tr>{{/each}}
</table>
在Handlebars中, 你甚至能访问内嵌属性, like in (Albums.0.Name). 当然你也可再使用一个each来loop你的数组. 你应该注意到了, 上面的例子中使用的 . 来访问属性, 你也能使用 ../ 来访问 父级的属性.
{{#if Bands}}<table><tr><th>Band Name</th><th>Date</th><th>Album Name</th></tr>{{#each Bands}}<tr><td>{{Name}}</td><td>{{Date}}</td><td>{{Albums.0.Name}}</td></tr>{{/each}}</table>{{else}}<h3>There are no concerts coming up.</h3>{{/if}}
-
- Function helpers 是基本的Function函数, 注册一次, 就可以在Handlebars template中的任何地方使用. Handlebars会写这个Function的回值到template上.
- Block helpers 是类似 if , each, etc 它们允许人改变 上面文里的
- 让我展示给你一个简单的例子. 首先, 我将会注册一个function helper 通过以下代码:
-
Handlebars.registerHelper("Max", function(A, B){ return (A > B) ? A : B; });这个 registerHelper的第一个参数是这个 helper 的名子, 我将会在template里使用它. 这个第二个参数, 是一个匿名函数. - 如何使用请看下面的例子:
-
{{Max 12 45}}这个template 使用 Max 语法 , 和解析 12 和 45 到这个函数里, Handlebars 函数 helper里支持多个参数, 你可以直接插入数据 到template本身, 或者你能使用Json结构的属性.
{
Name: "Parent",
Sub: {
Name: "Child"
}
}
这里有两个key相同的Name属性, 与一个Helper来实现 即可以调用父级的Name, 又可以调用 child的Name:
Handlebars.registerHelper("BothNames", function(context, options){
return options.fn(context) + options.fn(context.Sub);
});
template看起来像这样:
{{#BothNames this}}<h2>{{Name}}</h2>{{/BothName}}
这个结束的语法名称 是告诉Handlebars这是一个block helper,和关闭它。
<html>
<head><title>Handlebars Demo</title><scripttype="text/javascript"src="Handlebars.js"></script></head><body><scriptid="Handlebars-Template"type="text/x-handlebars-template"></script></body></html>
<script>var Ajax = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
Ajax.onreadystatechange = function () {
if (Ajax.readyState == 4 && Ajax.status == 200){//Parse the JSON datavar RecipeData = JSON.parse(Ajax.responseText);//Get the Template from abovevar Source = document.getElementById("Handlebars-Template").textContent;//Compile the actual Template filevar Template = Handlebars.compile(Source);//Generate some HTML code from the compiled Templatevar HTML = Template({ Recipes : RecipeData });//Replace the body section with the new code.document.body.innerHTML = HTML;}}
Ajax.open("GET","Recipe.php", true);
Ajax.send();</script>
这是通过一个template去动态的编译生成html。 理论上你可以直接把Json数据放到Handlebars中, 但是你运行时会出现跨域问题。 代替的方法是使用PHP里的echo把它变为一个JavaScript的变量.所以在运行这个模板之前我会将所以的操作分到"Recipe.php"里去做. 让我们看一下这个PHP文件。
matches;
//Cycle Through The Recipes and Get full recipe for each
foreach($Recipes as $Recipe)
{
$ID = $Recipe->id;
$R = json_decode(file_get_contents("http://api.yummly.com/v1/api/recipe/" . $ID . "?_app_id=" . $UserID . "&_app_key=" . $UserKey . "&images=large"));
//This is the data we are going to pass to our Template
array_push($Json, array(
Name => $R->name,
Ingredients => $R->ingredientLines,
Image => $R->images[0]->hostedLargeUrl,
Yield => $R->yield,
Flavors => $R->flavors,
Source => array(
Name => $R->source->sourceDisplayName,
Url => $R->source->sourceRecipeUrl
)
));
}
//Print out the final JSON object
echo json_encode($Json);
?>
<scriptid="Handlebars-Template"type="text/x-handlebars-template"><divid="Content"><h1>ΞRecipeCards<spanid='BOS'>Recipe search powered by<aid='Logo'href='http://www.yummly.com/recipes'><imgsrc='http://static.yummly.com/api-logo.png'/></a></span></h1>{{#each Recipes}}<divclass='Box'><imgclass='Thumb'src="{{{Image}}}"alt="{{Name}}"><h3>{{Name}} <aid='Logo'href="{{Source.Url}}"> - {{Source.Name}}</a></h3><h5>{{getFlavor Flavors}}</h5><h5>{{Yield}}</h5><p>Ingredients:</p><ul>{{#each Ingredients}}<li>{{this}}</li>{{/each}}</ul></div>
{{/each}}</div></script>
Handlebars.registerHelper("getFlavor", function(FlavorsArr){
var H = 0;
var Name = '';
for(var F in FlavorsArr)
{
if(FlavorsArr[F] > H)
{
H = FlavorsArr[F];
Name = F;
}
}
return "This Dish has a " + Name + " Flavor";
});
npm install handlebars -g你可能需要 root 权限, 安装完成, 你能为你的template创建一个文件和编译它像这样
handlebars demo.handlebars -f demo.js
var template = Handlebars.templates['demo'];
var html = template({ Your Json Data Here });
[1] Yummly: Yummly 是一个语义食谱搜索引擎,拥有50多万份食谱,用户可以根据口味、原料、价格、营养等搜索到所需要的食品。Yummly会根据用户过去的搜索,不断学习喜好,从而推荐可能会感兴趣的食品给你。
[2] Helper: 文章里使用的helper 是指Handlebars里有一个语法。
本文介绍了Handlebars模板引擎的基本概念,展示了如何使用Handlebars创建动态HTML页面,包括使用内置方法处理复杂数据,自定义语法,以及通过API获取数据并解析到模板中。
583

被折叠的 条评论
为什么被折叠?



