Ask the question about the implementation of the front-end template engine?

//
<div>{{ name + sex + "hello!" }}</div>
//js
data: {name: "joker", sex: "male"}

now we need to use a method tmpl (str, data) to get the result. How to implement the tmpl function, thank you?

Feb.04,2022

I happen to be working on this, too. I can take a look at an article written by someone else that has https://codeshelper.com/a/11.


var str = `<div>{{ name + sex + 'hello!' }}</div>`;
var data = { name: "joker", sex: "male" };
function tmpl(str, data) {
  return str.replace(/\{\{([\S\s]+)\}\}/g, (m, p1) =>
    p1.split("+").map(item => {
        item = item.trim();
        var reg = /^['"]([\s\S]+)['"]$/;
        return !reg.test(item) ? data[item] : item.replace(reg, "$1");
      }) .join('')
  );
}
that you want.
Menu