在browser瀏覽器中使用Handlebarshtml
1 基本語法jquery
<div class="demo"> <h1>{{name}}</h1> <p>{{content}}</p> </div>
2 經過script標籤放置模板express
<script type="text/template" id="avatarTpl">
<div class="info_block">
<div class="info_block_left">
<span>頭像修改</span>
</div>
<div class="info_block_right">
<div class="modify_avatar">
<div class="modify_avatar_left" id="avatar_drag_container">
<img src="/images/common/avatar_wrapper.png" alt="" class="p1">
<img src="/images/common/p3.jpg" alt="" class="p2">
</div>
<div class="modify_avatar_right">
<div class="modify_avatar_right_top">從電腦中選擇一張你的照片上傳</div>
<div class="modify_avatar_right_bot">
<div class="upload_btn" id="avatar_upload_container">
<input name="token" type="hidden" value="{{token}}">
<input name="key" type="hidden" value="{{qiniuKey}}">
<input type="file" id="avatar_upload">
上傳圖片
</div>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</script>
3 使用Handlebars.compile來預編譯模板npm
//用jquery獲取模板 var tpl = $("#tpl").html(); //原生方法 var source = document.getElementById('#tpl').innerHTML; //預編譯模板 var template = Handlebars.compile(source); //模擬json數據 var context = { name: "zhaoshuai", content: "learn Handlebars"}; //匹配json內容 var html = template(context); //輸入模板 $(body).html(html);
4 內置helperjson
withgulp
改變做用域瀏覽器
eachapp
數據循環框架
if else helper 條件渲染ui
判斷條件成立
1 {{#if list}} 2 <ul id="list"> 3 {{#each list}} 4 <li>{{this}}</li> 5 {{/each}} 6 </ul> 7 {{else}} 8 <p>no list</p> 9 {{/if}}
不過內置的helper都很差用,通常咱們須要自定義新的helper
Handlebars.registerHelper("debug", function(optionalValue) { //do sth });
有用的tips
Node express中使用handlebars
使用hbs的npm包
var hbs = require('hbs')
app.set('view engine', 'hbs');
// 註冊partial __dirname是當前目錄 partials目錄下放置全部的公共partials 經過{{}}引用
hbs.registerPartials(__dirname + '/views/partials');
建立layout.hbs
//隱藏了html的框架 其中header body footer都是公用的內容
<body>
{{> header}} {{{body}}} {{> footer}}</body>