一層的渲染
將下面的模板中的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}...
}