0.1.0 • Published 10 years ago

x-template v0.1.0

Weekly downloads
3
License
ISC
Repository
github
Last release
10 years ago

$template 字符串模板库

$template是一个简单高效的字符串模板引擎,有关解析表达式的部分参考了ng里的$parse服务.

字符串替换

$template提供了es6里的字符串模板功能,用法如下

  $template.template('hello {{name}}', { name: 'feenan'}); // => hello feenan

支持四则运算

//  + - *  /

$template.template('(1+2)*age = {{ (1+2)*age}}', {age: 18}); // => (1+2)*age = 54

支持各种比较操作符

// > < >= <= == === !== !=
$template.template('1>2', {}); // => false

$template.template('age > 18', {age: 20}); // => true

支持三元运算符

$template.template('{{ 2 > 1 ? name : ""}}', {name: 'feenan'}); // => feenan

条件判断if

$template支持if语句来判断是否显示字符串的某部分,这里采用<% %>来显示程序语法

	<p>check if statment</p>
	<% if(showFn()) { %>
		<h1>hello1 {{ user.name }}</h1>
		<% if(user.age == 1) { %>
			<h2>hello2 {{ user.action | substr:1}}</h2>
		<% } %>
		<% if(user.age == 1) { %>
			<h3>hello3 {{ user.action }}</h3>
			<% for(user in users) {%>
				<h1>hello {{user.name}}</h1>
			<% } %>
			<% if(user.age == 1) { %>
				<h4> hello4 {{ user.name}}</h4>
			<% } %>
		<% } %>
	<% } %>	
var fn = $template.template(html);
var data = {
	showFn: function(){
		return true;
	},
	showh1: true,
	user: {
		name: 'feenan',
		info: 'haha',
		action: 'start',
		age: 2
	},
	users:[
		{name: 'feenan', info: 'haha'},
		{name: 'feenan1', info: 'haha1'}
	]
}
fn(data);

注意: 假如$template.template只传递字符串的话会返回一个编译函数,下次传递数据才会生成最后的字符串.

目前if语句支持无限嵌套if语句,支持嵌套for语句.

	<% if(user.age > 1) {%>
		<% for(user in users) {%>
			<h1>hello {{user.name}}</h1>
		<% } %>
		<% for(user in users) {%>
			<h2>hello {{user.name}}</h2>
		<% } %>
	<% }%>

循环语句for

目前for语句支持无限嵌套if语句,支持嵌套for本身.

	<% for(user in users) {%>
		<h1>hello {{user.name}}</h1>
		<% if(user.name) { %>
			<h2>hello2 {{ user.info}}</h2>
		<% } %>
		<% for(action in user.actions) {%>
			<h3>hello 3 {{action.name}}</h3>
		<% }%>
	<% } %>

过滤函数

目前支持以管道符号|来执行过滤函数,对外提供扩展属性的方式来增加自定义过滤函数.扩展属性通过$template.methods数组来实现.

$template.methods.push(['int', function(src, len){
	var str  = String(src).substr(0, len);
	return Number(str);
}]);

$template.template('your age is {{ age | int:5 }}', { age: '50'}); // => 50

过滤函数支持传递参数,方法名后面传递:后跟值就可以.

待改进的地方

  • if语句增加else功能
  • 增加字符串安全过滤功能

总结

现在模板引擎非常多,希望这个小小的js库大家会喜欢,有问题可以提github上.

0.1.0

10 years ago

0.0.9

10 years ago

0.0.8

10 years ago

0.0.7

10 years ago

0.0.6

10 years ago

0.0.5

10 years ago

0.0.4

10 years ago

0.0.3

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago