Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ tppl.js
<script id="test" type="text/html">
[: if (title){ :]
[: for (var i=0;i<list.length;i++) { :]
<div>[=:i:]. [=:list[i].user:]</div>
<div>[=:i:]. [=:list[i]:]</div>
[:}:]
[=:this.name||"name is not found !":]
[:}:]
Expand Down Expand Up @@ -59,6 +59,16 @@ tppl.js
var html = render(data); //重复使用
var html = render(data, true); //极速模式渲染

#### tppl.helper(name, handler)

参数`name`表示helper的名称。

参数`handler`表示处理函数。

注册helper需要在调用tppl方法之前使用才有效。

返回处理后的字符串

============

## 语法
Expand All @@ -70,6 +80,12 @@ closeTag | String | ``:]`` | 逻辑语法结束标签
valueTag | String | ``[=:`` | 输出变量开始标签
valueTag | String | ``:]`` | 输出变量结束标签

**helper语法**

在模板中,通过`单斜杠`方式调用注册好的helper:

[=: foo | wordFormat:'formateParam' :]

**变量默认值**

为未定义的或值为`假`的变量给出默认值:
Expand Down
38 changes: 37 additions & 1 deletion tppl.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,47 @@ function tppl(tpl, data, fast){
fn.$ += p.substr(0, x);
p = p.substr(x+2)
}
fn.$ += "$+='"+p.replace(/\[\=\:(.*?)\:\]/g, "'+$1+'")+"';";


fn.$ += "$+=('"+p.replace(/\[\=\:(.*?)\:\]/g,function(str,$1){
var f = $1.split("|")[1];
var v = $1.split("|")[0].trim();
if(f&&f.indexOf("|")==-1){
var h = f.split(":")[0]&&f.split(":")[0].trim();
var pa = f.split(":")[1]&&f.split(":")[1].trim();
return "'+tppl.helpers[\'"+h+"\']("+v+","+pa.replace(/\\'/g,"'")+")+'";
}else{
return "'+"+$1+"+'"
}
})+"');\n";

i++;
}
fn.$ += "return $";
}

return data ? fn(data) : fn;
}

/**
* 模板helper,让模板具有更加强大的功能。
* 作者:Moejser
* 邮箱:i@moejser.com
* 在渲染模板之前调用tppl.helper方法注册helper
* @param name {String} helper名是不可重复的,重复定义会被覆盖。
* @param handler {Function} 对传入的数据进行处理的函数,这个函数会接受到两个参数:1.被处理的值,2.格式化标志位
*
* Usage:
* tppl.helper("say",function(title,format){
* return title+format;
* })
*
* @return {String} 处理后的字符串
*/

tppl.helpers = {};
tppl.helper = function(name, handler){
if(name&&hanler){
tppl.helpers[name] = handler;
}
}