一层的渲染
将下面的模板中的mustache语法使用给定数据渲染.
模板如下
<div id="root"><div><div><p>{{name}} - {{message}}</p></div></div><p>{{name}}</p><p>{{msg}}</p>
</div>
数据如下
const data = {name: '一个新name',message: '一个消息',msg: '哈哈哈'
}
思路
- 首先使用
document.querySelector
方法获取DOM结构 - 然后得到其所有的子元素,通过节点类型(
node.nodeType
)来判断其是文本节点还是元素节点 - 如果是文本节点,则使用正则表达式来判断,文本值中是否有mustache语法.
- 如果有则用data中的数据去替换它
知识点
- 使用正则表达式来判断是否含有
{{}}
, 若有解析出其中的值.使用data中的值替换
const mustache = /\{\{(.+?)\}\}/g; // 这个正则规则匹配`{{}}`,其中(.+?)代表任意的字符
// 获取文本节点的值, 假设是 `<p>{{ name }}</p>`
let txt = textNode.nodeValue
txt = txt.replace(mustache, function(_, g){return data[g.trim()] // data = {name: '一个新name'}
})
实现
const mustache = /\{\{(.+?)\}\}/g;
let tmpNode = document.quertSelector('#root')
let data = {name: '一个新name',message: '一个消息',msg: '哈哈哈'
}
function compiler(template, data) {let childNodes = template.childNodesfor(let i = 0 , len = childNodes.length; i < len ; i++){let nodeType = childNodes[i].nodeTypeif(type == 3 ){// 文本节点let txt = childNodes[i].nodeValue;// 得到替换后的文本txt = txt.replace(mustache, function(_, g){return data[g.trim()]})// 将替换后的文本放到DOM中childNodes[i].nodeValue = txt} else if(type == 1) {compiler(childNodes[i], data)}}
}
深层次的渲染
- 上面的函数只能替换简单对象,而不能替换引用类型的对象
- 即:
a.name
之类的就无法替换 - 需要使用对象深层次遍历的方法
- 根据路径得到对象中的值
function getValueByPath(obj, path){let res = obj,currProp,props = path.split('.')while((currProp = props.shift())){if(!res[currProp]){return undefined} else {res = res[currProp]}}return res
}
function compiler(template, data){// 其他位置和上述一样// 仅改写文本节点中的...if(type == 3){// 文本节点let txt = childNodes[i].nodeValue// 得到替换后的文本txt = txt.replace(mustache, function(_, g){return getValueByPath(data, g.trim())})childNodes[i].nodeValue = txt}...
}