Created
June 25, 2017 14:07
-
-
Save zdying/4e80a5805aeb11cade41e4474b9cf9db to your computer and use it in GitHub Desktop.
simple template engine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.clear(); | |
function render(template, data){ | |
console.info('render ==>', template, data); | |
template = template.replace(/\{\{([#^])([^}]+?)\}\}(?:([\s\S]*?)\{\{\/(\2+?)\}\})?/g, function (match, ope, key, content, key1) { | |
if (key !== key1) { | |
throw Error(key + ' and ' + key1 + ' does not match.'); | |
} | |
var value = getValue(data, key); | |
var isArray = Array.isArray(value); | |
var result = ''; | |
if(isArray){ | |
return value.map(function(val){ | |
if(typeof val !== 'object'){ | |
val = { | |
'.': val | |
} | |
} | |
val.__parent__ = data; | |
return render(content, val); | |
}).join(''); | |
}else if(value){ | |
return render(content, data); | |
}else{ | |
return ''; | |
} | |
}); | |
return template.replace(/\{\{([^/^#}]+?)\}\}/g, function(match, key) { | |
// if(key === '.'){ | |
// return data; | |
// } | |
return getValue(data, key); | |
}) | |
} | |
function getValue(obj, key){ | |
var value = obj; | |
var keys = key.split('.'); | |
var curr = null; | |
if(key === '.'){ | |
return obj['.']; | |
} | |
while(curr = keys.shift()){ | |
value = value[curr]; | |
} | |
if (value === undefined && obj.__parent__) { | |
console.log('parent::', obj); | |
value = getValue(obj.__parent__, key); | |
} | |
return value; | |
} | |
var template = `<div> | |
<span>{{name}}</span> | |
<span>{{age}}</span> | |
<span>{{address.city}}</span> | |
{{#age}}age is ture{{/age}} | |
{{#age1}}age1 is ture{{/age1}} | |
<ul> | |
{{#list}} | |
<li>{{title}}-{{age}} {{#arr}} _{{age}} {{.}}_ {{/arr}}</li> | |
{{/list}} | |
</ul> | |
</div> | |
`; | |
var data = { | |
name: 'zdying', | |
age: 20, | |
age1: 0, | |
address: { | |
country: 'China', | |
city: 'Beijing' | |
}, | |
list: [ | |
{title: 'title a', arr: [1, 2, 3]}, | |
{title: 'title b', arr: [4, 5, 6]} | |
] | |
} | |
console.log(render(template, data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment