$template 字符串模板库
$template
是一个简单高效的字符串模板引擎,有关解析表达式的部分参考了ng
里的$parse
服务.
字符串替换
$template
提供了es6
里的字符串模板功能,用法如下
$template; // => hello feenan
支持四则运算
// + - * / $template; // => (1+2)*age = 54
支持各种比较操作符
// > < >= <= == === !== !=$template; // => false $template; // => true
支持三元运算符
$template; // => feenan
条件判断if
$template
支持if
语句来判断是否显示字符串的某部分,这里采用<% %>
来显示程序语法
check if statment <% if(showFn()) { %> hello1 {{ user.name }} <% if(user.age == 1) { %> hello2 {{ user.action | substr:1}} <% } %> <% if(user.age == 1) { %> hello3 {{ user.action }} <% for(user in users) {%> hello {{user.name}} <% } %> <% if(user.age == 1) { %> hello4 {{ user.name}} <% } %> <% } %> <% } %>
var fn = $template;var data = { return true; } showh1: true user: name: 'feenan' info: 'haha' action: 'start' age: 2 users: name: 'feenan' info: 'haha' name: 'feenan1' info: 'haha1' ;
注意: 假如
$template.template
只传递字符串的话会返回一个编译函数,下次传递数据才会生成最后的字符串.
目前if
语句支持无限嵌套if语句
,支持嵌套for
语句.
<% if(user.age > 1) {%> <% for(user in users) {%> hello {{user.name}} <% } %> <% for(user in users) {%> hello {{user.name}} <% } %> <% }%>
循环语句for
目前for
语句支持无限嵌套if
语句,支持嵌套for
本身.
<% for(user in users) {%> hello {{user.name}} <% if(user.name) { %> hello2 {{ user.info}} <% } %> <% for(action in user.actions) {%> hello 3 {{action.name}} <% }%> <% } %>
过滤函数
目前支持以管道符号|
来执行过滤函数,对外提供扩展属性的方式来增加自定义过滤函数.扩展属性通过$template.methods
数组来实现.
$templatemethods; $template; // => 50
过滤函数支持传递参数,方法名后面传递:
后跟值就可以.
待改进的地方
if
语句增加else
功能- 增加字符串安全过滤功能
总结
现在模板引擎非常多,希望这个小小的js
库大家会喜欢,有问题可以提github
上.