Features
- 语法继承自KISSY 1.2 Template ,不过少了个花括号
- 编译后的代码非常直观 Temple编译后的代码
- 基本的 if/elseif/else each
- include 子模板
- extend 模板继承
- if(exp) exp可以为复杂表达式
- 模板允许使用自定义函数
Getting Started
KISSY.use('gallery/temple/1.0/index', function (S, Temple) {
Temple.add("base","this is head , my sex is {#block name} female {/block}!");
var temple = Temple.compile('{#extend base} {#block name} {sex} {/block}');
var html = temple.render({"sex":"male"});
console.log(html);
})
API
Temple.compile
将模板编译为可以直接执行的js函数,返回的对象具有render方法
Temple.to_js
将模板编译为js代码字符串,用于调试或者预编译
语法示例
expression and variable
var s = '{#if (a+(b-c*d/(ef%3)))}'
+ 'blah blah {lib}'
+ '{/if}';
var temple = Temple.compile(s);
temple.render({a:1,b:2,c:3,d:4,ef:5,lib:"KISSY"});
// => "blah blah KISSY"
if
var template = '{#if name}'
+ 'hi {name}'
+ '{/if}'
var temple = Temple.compile(template);
temple.render({name:"tom"});
// -> tom
if/else
var template;
template = '{#if name}'
+ '{name}'
+ '{#else}'
+ 'noname'
+ '{/if}'
var temple = Temple.compile(template);
template.render({name:"tom"});
if/elseif/else
template = '{#if name}'
+ '{name}'
+ '{#elseif sex}'
+ '{sex}'
+ '{#else}'
+ 'oops'
+ '{/if}'
var temple = Temple.compile(template);
temple.render({name:"tom"});
// => tom
each
var template = '{#each items as item index}'
+ '{index} : {item.name}'
+ '{/each}';
var temple = Temple.compile(template);
temple.render({items:[{name:"john"}]});
// => "0 : john"
include
Temple.add("head","<h1>共用头</h1>");
Temple.add("foot","<h1>共用脚</h1");
var template = '{#include head}'
+ '<p>身体是你自己的</p>'
+ '{#include foot}';
var temple = Temple.compile(template);
temple.render();
// => "<h1>共用头</h1><p>身体是你自己的</p><h1>共用脚</h1"
extend
Temple.add("base","<h1>共用头</h1>"
+ "{#block body}"
+ "<p>大家都公用的身体</p>"
+ "{/block}"
+ "<h1>共用脚</h1>");
var app = '{#extend base}'
+ '{#block body}'
+ '<p>你自己的身体</p>'
+ '{/block}';
var temple;
temple = Temple.compile(app);
temple.render();
// => "<h1>共用头</h1><p>你自己的身体</p><h1>共用脚</h1>"
custom function
Temple.reg("myescape",function(s){
return escape(s);
});
var temple = Temple.compile('{myescape(htmlstr)}');
temple.render({htmlstr:"<p>foo</p>"});
// => "%3Cp%3Efoo%3C/p%3E"
var temple;
temple = Temple.compile('{#!this is a line of comment}');
temple.render();
// => ""
temple = Temple.compile('{#! 可以包含"{"、"#"、"\\}" }');
temple.render();
// => ""
temple = Temple.compile('{#! 中文注释} 中文字符串abc');
temple.render();
// => " 中文字符串abc"