Skip to content

Instantly share code, notes, and snippets.

@guiqide
Last active September 19, 2019 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guiqide/e9c317591a2d24d0f5cff8e4f49230a1 to your computer and use it in GitHub Desktop.
Save guiqide/e9c317591a2d24d0f5cff8e4f49230a1 to your computer and use it in GitHub Desktop.
正则——实现js模板引擎
// 别看这个模板引擎代码很少,但是活用了正则、将字符串转为可以行代码两个知识点
const a = {
a: 1,
b: {
c: 2,
e: ['Array']
}
}
const tpl = `你好{{ a ? '真' : '假'}}
{{b.c}}}11{{b.e[0]}}{{}}`
const render=(tpl, a) => {
return tpl.replace(/{{2}([^{}]*?)}{2}/g, function (s0, s1) {
if (s1 === '') {
return ''
}
const data = new Function(`return this.${s1}`).apply(a)
return data
})
}
console.log(render(tpl, a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment