간단한 js 템플릿
3438 단어 JS 템플릿
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Simple Templating</title>
</head>
<body>
<div id="content" style="border:1px solid red;"></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;
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));
document.querySelector("#content").innerHTML=_template(template, data);
</script>
</body>
</html>
자신의 업무 사용이 개선되었다
/
function _temp(template, data){
var i = 0,
fragment = '';
function status(v){
var str =v ;
if(v==0){
str=" ";
}else if(v==1){
str=" ";
}else if(v==2){
str=" ";
}else if(v==3){
str=" ";
}else if(v==4){
str=" ";
}else if(v==5){
str=" ";
}else if(v==6){
str=" ";
}
return str;
}
function replace(obj){
var t, key, reg,v;
for(key in obj){
reg = new RegExp('{{' + key + '}}', 'ig');
if(key=="STATUS"){
v=status(obj[key]);
}else if(key=='LOAN_DATE'){
v=new Date(obj[key]).format("yyyy-MM-dd hh:mm:ss");
}else if(key=='LOAN_EXPIRE'){
v=new Date(obj[key]).format("yyyy-MM-dd");
}else{
v=obj[key];
}
t = (t || template).replace(reg, v);
}
return t;
}
fragment += replace(data);
return fragment;
}