Handlebars
虽然skylarkjs没有提供模板引擎功能,但开发者可以集成任何模板引擎,用于日常的开发,本文介绍了为skylarkjs引入handlebars的相关知识。
创建应用
sjs create handlebars-demo --routes home:/
引入模块
可以通过AMD的方式,在入口配置文件(slax-config.json)中引入handlebars模块。
...... "paths": { ...... "handlebars": "https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.amd.min" } .....
定制Controller
scripts/routes/HomeController.js
define([ "skylarkjs", "handlebars", "text!scripts/data/items.json", "text!scripts/routes/home/home.hbs" ], function(skylarkjs, handlebars, itemsJson, homeTpl) { var spa = skylarkjs.spa, langx = skylarkjs.langx, $ = skylarkjs.query; return spa.RouteController.inherit({ klassName: "HomeController", rendering: function(e) { var items = JSON.parse(itemsJson), selector = $(langx.trim(homeTpl)); handlebars.registerPartial("item-partial", langx.trim(selector.find("#item-partial").html()).replace(/\{\{>/g, "{{>")); handlebars.registerPartial("list-partial", langx.trim(selector.find("#list-partial").html()).replace(/\{\{>/g, "{{>")); var tpl = handlebars.compile(langx.trim(selector.find("#main").html()).replace("{{>", "{{>")); e.content = tpl({ items: items }); }, entered: function() {}, exited: function() {} }); });
定制view
<div> <script id="main" type="text/x-handlebars-template"> <div class="container"> <ul class="items"> {{> list-partial}} </ul> </div> </script> <script id="list-partial" type="text/x-handlebars-template"> {{#each items}} {{> item-partial}} {{/each}} </script> <script id="item-partial" type="text/x-handlebars-template"> <li>{{name}}</li> </script> </div>