Last active
September 19, 2019 02:08
-
-
Save guiqide/e9c317591a2d24d0f5cff8e4f49230a1 to your computer and use it in GitHub Desktop.
正则——实现js模板引擎
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 别看这个模板引擎代码很少,但是活用了正则、将字符串转为可以行代码两个知识点 | |
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