Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
barretTpl Demo
<!DOCTYPE HTML>
<body>
<style type="text/css">
textarea, button, div {
display: inline-block;
vertical-align: middle;
margin-right:30px;
}
textarea {
width:500px;
height:140px;
}
#container {
width:220px;
height:110px;
padding:15px;
border: 1px dashed #CCC;
}
</style>
<textarea id="barretDemo">
<% for(var i = 0; i < this.posts.length; i++) {
var post = this.posts[i]; %>
<% if(!post.expert){ %>
<span>post is null</span><br />
<% } else { %>
<a href="#"><% post.expert %> at <% post.time %></a><br />
<% } %>
<% } %>
</textarea>
<button id="btn">输出</button>
<div id="container"></div>
<script>
var data = {
"posts": [{
"expert": "content 1",
"time": "yesterday"
},{
"expert": "content 2",
"time": "today"
},{
"expert": "content 3",
"time": "tomorrow"
},{
"expert": "",
"time": "eee"
}]
};
var barretTpl = function(str, data) {
//获取元素
var element = document.getElementById(str);
if (element) {
//textarea或input则取value,其它情况取innerHTML
var html = /^(textarea|input)$/i.test(element.nodeName) ? element.value : element.innerHTML;
return tplEngine(html, data);
} else {
//是模板字符串,则生成一个函数
//如果直接传入字符串作为模板,则可能变化过多,因此不考虑缓存
return tplEngine(str, data);
}
function tplEngine(tpl, data) {
var reg = /<%([^%>]+)?%>/g,
regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
code = 'var r=[];\n',
cursor = 0;
var add = function(line, js) {
js? (code += line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n') :
(code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
return add;
}
while(match = reg.exec(tpl)) {
add(tpl.slice(cursor, match.index))(match[1], true);
cursor = match.index + match[0].length;
}
add(tpl.substr(cursor, tpl.length - cursor));
code += 'return r.join("");';
console.log(code);
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
};
};
document.getElementById("btn").onclick = function(){
document.getElementById("container").innerHTML = barretTpl("barretDemo",data);
}
</script>
</body>
@786320861

This comment has been minimized.

Copy link

@786320861 786320861 commented Apr 11, 2016

看过啦,我借鉴一下哈

@Niefee

This comment has been minimized.

Copy link

@Niefee Niefee commented Jun 30, 2017

学习了,厉害

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment