Post on 12-Sep-2014
description
KISSY xtemplate
• Another Template Engine
• Docs: – http://docs.kissyui.com/docs/html/api/componen
t/xtemplate/
• Development Source: – https://github.com/kissyteam/kissy/tree/master/s
rc/xtemplate
功能简介
• 变量渲染/转义
• 表达式
• 控制语句
• 层次访问
• 命令扩展
• 子模板
• 报错
变量渲染
• {{x}}
• {{{x}}}
表达式
• + - * / %
• && || === >= <=
• {{x+2}}
• {{#if x>2}}
控制语句
• {{#if}}{{/if}}
• {{#each}}{{xindex}}{{this}}{{/each}}
• {{#with obj}}{{y}}{{/with}}
• obj.y.z
层次访问
• {{#with y}}{{../../x}}{{x}}{{/each}}
• {
x: 1,
y: {
x: 2
}
}
命令扩展
• {{myCommand 1 2 3 4 x x+2 x*3}} • {{#my xx}}{{x}}{{y}}{{/my}}
• function myCommand(scopes,option){
option.params //=> [‘x’,1] option.hash // {y:2} scopes.unshift({ xindex: 1}); “html”+option.fn(scopes,)+”end” return “xxx”; }
子模板
• {{include ‘x-tpl’}}
• x-tpl
– {{x}}
• 1.3
– Xtemplate.addSubTpl(‘x-tpl’,’{{x}}’)
range
• {{set x=1}}
• Array [1 .. 10]
• {{#range x y}}{{/range}}
报错处理
• ‘{{x}}\n{{y’
• xx.tpl
• {{x}}\n{{y
------------^ unclosed error at line 2
实现
• 设计语法
• 生成解析器
• 翻译代码
• 执行引擎
• 划分模块
设计语法
• {{mustache}}
• 词法
• 语法
词法
• 识别基本元素
• Open
• Id
• operator
语法
• 描述程序结构
• lalr
• Program
• Statement xx
• Tpl {{x}}
解析器生成
• kison
– https://github.com/kissyteam/kissy/tree/master/src/kison
–解析器生成工具
• 词法+语法 -> kison -> parse.js
parser.js
• module
• parse()
–标记语法树
– parse(‘my\n{{x}}’)
program
Content:
line:1
value: my\n
tpl:
line:2
Id:
line:2
value: x
翻译代码
• 遍历序列化生成 js 函数
• var source = “var out=[];”;
If(node.type == ‘id’){
source+=‘out.push(context.’+ node.name+’)’;
} else { … }
source+=‘return out.join(“”);’;
执行
• {{my}}
• new Function(“context”, source)({my:1});
划分模块
• xtemplate/compiler 翻译代码
–离线 (工具编译)
–在线(客户端浏览器)
• xemplate runtime
–在线
• xtemplate requires [‘compiler’, ‘runtime’]
展望
• 功能
–模板与模块
• {{include “x/y”}}
– x/y.js
• KISSY.add(‘x/y’, ‘{{x}}{{include “x/z”}}’,{requires:[‘x/z’]});
展望
• 功能
– extend
• Layout.tpl – {{header}}
{{#override content}}<b>{{x}}</b>{{/override }}
- Item2.tpl
{{extend layout}}
• Item1.tpl – {{extend layout}}
{{#override content}} <i>{{x}}</i>{{/override }}
展望
• 前后端统一模板
–同步渲染
• Java/php
–异步渲染 • Js
• 同一套语法,离线翻译成不同语言的原生实现
展望
• 数组类型支持
• Range 命令
• python django jinja2
• jade