请问reder里应该怎么写
拿去玩。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="template" class="{{className}}">
<div class="user_profile">
<div class="user_avatar">
<img src="{{user.avator}}" alt="">
</div>
{{user.name}}
</div>
</div>
</body>
<script>
function render(template, context) {
var tokenReg = /(\\)?\{\{([^\{\}\\]+)(\\)?\}\}/g;
return template.replace(tokenReg, function(word, slash1, token, slash2) {
if (slash1 || slash2) {
return word.replace('\\', '');
}
var variables = token.replace(/\s/g, '').split('.');
var currentObject = context;
var i, length, variable;
for (i = 0, length = variables.length; i < length; ++i) {
variable = variables[i];
currentObject = currentObject[variable];
if (currentObject === undefined || currentObject === null) return '';
}
return currentObject;
})
}
var m = {
className: 'user',
user: {
name: 'xiaoming',
avator: 'http://imgsrc.baidu.com/forum/pic/item/ab64034f78f0f736d0d308f60255b319ebc41313.jpg'
}
}
var template = document.getElementById('template').outerHTML;
document.getElementById('template').outerHTML = render(template, m)
</script>
</html>
精简版,不考虑\\
,容错率略低,供参考。
function render(el, modal) {
// 利用正则获取所有形如{{...}}的字符串进行替换
el.outerHTML = el.outerHTML.replace(/{{([^}]+)}}/g, function(str, keys) {
// 去掉字符串多余的空格,用“.”切分成数组
return keys.trim().split('.').reduce(function(a,b){
// 以数组的每一个元素作为对象属性名,获取子对象
return a[b] || "";
// reduce对象的初始值设为modal
}, modal);
})
}
一个不破坏dom结构的实现
function render(el, model) {
function renderElement(el) {
Array.from(el.attributes).forEach(renderAttr);
Array.from(el.childNodes).forEach(function (node) {
if (node instanceof Text)
renderText(node);
if (node instanceof Element)
renderElement(node);
});
}
function renderText(text) {
text.data = renderStr(text.data);
}
function renderAttr(attr) {
attr.value = renderStr(attr.value);
}
function renderStr(str) {
return str.replace(/(\\)?\{\{(.*?)(\\)?\}\}/g, function (word, pre, token, post) {
if (pre || post) {
return word.replace('\\', '');
}
var value = token
.replace(/\s/g, '')
.split('.')
.reduce(function (context, member) {
if (context === null || context === undefined)
return;
else
return context[member];
}, model);
if (value === null || value === undefined)
return '';
else
return value;
});
}
renderElement(el);
}
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
就是把模板节点内包含的所有节点中有模板标记值的用正则找出来,然后用数据模型的值去替换掉呀