模板编译

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const template = `
<div class="play" name="{{name}}">{{ value }}</div>
`

const data = {
name: 'Brolly',
value: 'FE'
}

const compiler = (str, data) => {
const reg = /\{\{(.*?)\}\}/g
return str.replace(reg, (patten, g1) => {
const key = g1.trim()
return data[key] ? data[key] : ''
})
}

const content = compiler(template, data)
// <div class="play" name="Brolly">FE</div>
console.log(content)