Link
Embed
Share
Beginning
This slide
Copy link URL
Copy link URL
Copy iframe embed code
Copy iframe embed code
Copy javascript embed code
Copy javascript embed code
Share
Tweet
Share
Tweet
Slide 1
Slide 1 text
xtemplate internal
[email protected]
承玉
Slide 2
Slide 2 text
xtemplate • Yet Another Extensible Template Engine • Docs: – http://kissyteam.github.io/xtpl • Development Source: – https://github.com/kissyteam/xtemplate
Slide 3
Slide 3 text
功能简介 • 变量渲染/转义/设置 • 表达式 • 控制语句 • 层次访问 • 子模板 • 继承 • 宏 • 命令扩展 • 报错
Slide 4
Slide 4 text
变量渲染 • {{x}} – S.escapeHtml • {{{x}}} • {{set x=1}}
Slide 5
Slide 5 text
表达式 • + - * / % • && || === >= <= • {{x+2}} • {{#if (x>2)}}xxx{{/if}}
Slide 6
Slide 6 text
控制语句 • {{#if (x)}}{{/if}} • {{#each (x)}}{{xindex}}{{this}}{{/each}} • {{#with (obj)}}{{y}}{{/with}} – {{obj.y}}
Slide 7
Slide 7 text
层次访问 • {{#each (y)}}{{../../x}}{{x}}{{/each}} • { x: 1, y: [{ x: 2 }] }
Slide 8
Slide 8 text
子模板 • {{include (‘./x-tpl’)}} • x-tpl.html – {{x}} {{#each}}
Slide 9
Slide 9 text
继承 • Layout.xtpl – {{#block(‘default’)}}default{{/block}} – {{block(‘header’)}} • Page.xtpl – {{extend(‘./layout.xtpl’)}} – {{#block(‘header’)}}header{{/block}}
Slide 10
Slide 10 text
宏 // 声明 {{#macro("test","param" default=1)}}param is {{param}} {{default}}{{/macro}} // 调用宏 {{macro("test","2")}} // => param is 2 1 {{macro("test", "2", 2)}} // => param is 2 2
Slide 11
Slide 11 text
命令扩展 • 同步 • 异步 • 块状 • 行内
Slide 12
Slide 12 text
报错处理 • {{x}}\n{{y ------------^ unclosed error at line 2
Slide 13
Slide 13 text
实现 • 设计语法 • 生成解析器 • 翻译代码 • 执行引擎 – 划分模块
Slide 14
Slide 14 text
设计语法 • {{mustache}} • 词法 • 语法
Slide 15
Slide 15 text
词法 • 识别基本元素 • Open • Id • operator
Slide 16
Slide 16 text
语法 • 描述程序结构 • Program • Statement xx • Tpl {{x}}
Slide 17
Slide 17 text
解析器生成 • kison – https://github.com/yiminghe/kison – LALR 解析器生成工具 • 词法+语法 -> kison -> parse.js
Slide 18
Slide 18 text
parser.js • module • parse() – 标记语法树 – parse(‘my\n{{x}}’) program Content: line:1 value: my\n tpl: line:2 Id: line:2 value: x
Slide 19
Slide 19 text
翻译代码 • 遍历语法树序列化生成 js 函数 var source = “var buffer = new LinkedBuffer().head;”; If(node.type == ‘id’){ source+=‘buffer.write(context.’+ node.name+’)’; } else { … } source+=‘return LinkedBuffer’;
Slide 20
Slide 20 text
执行 • {{my}} • new Function(“context”, source)({my:1});
Slide 21
Slide 21 text
模板渲染拼接
Slide 22
Slide 22 text
include/extend 加载 • nodejs – fs.readFile • Browser – a includes b // a.xtpl modulex.add(function(require){ return function(){ require('./b'); }; }) // b.xtpl .add(function(){ return function(){}; });
Slide 23
Slide 23 text
模块划分 • xtemplate/compiler 翻译代码 – 离线 (工具编译) – 在线(客户端浏览器) • xtemplate runtime – 运行环境 • xtemplate requires [‘compiler’, ‘runtime’]
Slide 24
Slide 24 text
standalone • 完全无依赖,即放即用 • https://github.com/kissyteam/xtemplate/blob /master/build/xtemplate-standalone-debug.js •
Slide 25
Slide 25 text
• Questions?