在编程中总是会遇见很多动态生成的东西,一般我们都是通过简单的html拼接起来的
function createHtml(name, phone, addr, email, imageSrc){
var html = '';
html += '<div class=personInfo>'
html += '<p>Name: ' + name + '</p>';
html += '<p>Phone: ' + phone + '</p>';
html += '<p>Addr: ' + addr + '</p>';
html += '<p>Email: ' + email + '</p>';
html += '<img src="' + imageSrc + '">';
html += '</div>'
return html;
}
但是其实我们可以通过使用正则表达式来进行简单的替换,从而实现模板解析
<script type="template" id="template">
<h2>
<a href="{{href}}">
{{title}}
</a>
</h2>
<img src="{{imgSrc}}" alt="{{title}}">
</script>
function replace(obj){
var t, key, reg;
for(key in obj){
reg = new RegExp('{{' + key + '}}', 'ig');
t = (t || template).replace(reg, obj[key]);
}
return t;
}
来一份简单的源代码:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Simple Templating</title>
</head>
<body> <div class="result"></div> <script type="template" id="template">
<h2>
<a href="{{href}}">
{{title}}
</a>
</h2>
<img src="{{imgSrc}}" alt="{{title}}">
</script> <script type="text/javascript">
var data = [
{
title : 'php web appliaction',
href : 'http://www.baidu.com',
imgSrc : 'http://www.baidu.com'
},
{
title : 'js 权威指南',
href : 'http://www.qq.com',
imgSrc : 'http://www.qq.com'
}];
var template = document.querySelector('#template').innerHTML,
result = document.querySelector('.result');
function _template(template, data){
var i = 0,
len = data.length,
fragment = '';
function replace(obj){
var t, key, reg;
for(key in obj){
reg = new RegExp('{{' + key + '}}', 'ig');
t = (t || template).replace(reg, obj[key]);
}
return t;
}
for(; i < len; i++){
fragment += replace(data[i]);
}
return fragment;
}
console.log(_template(template, data));
</script>
</body>
</html>