使用扩展运算符的模板函数

时间:2018-02-12 21:19:50

标签: javascript ecmascript-6 ecmascript-5

我并没有试图在这里重新发明轮子,只是玩弄了一个问题。我该如何编写一个简单的模板引擎函数。我的直接回答是更老的学校,但是使用ES6和新的传播运算符,让我想到现在使用扩展运算符可能有更好的方法。 有人有任何想法吗?或者我仍然需要遍历并找到我的分隔符,就像我使用下面的const delimiter =' {{name}}';

    const root = document.getElementById('root');
    const html = "<p>My name is {{ name }}</p>";

    var template = function(html){
      return function(data){
        for(var prop in data){
          var regx = "{{\\s?" + prop + "\\s?}}";
          html = html.replace(new RegExp(regx, "ig"), data[prop]);  
        }
        return html;
        }
    }

    var tmp = template(html);
    root.innerHTML = tmp({
      name: "John Doe"
    });;

1 个答案:

答案 0 :(得分:0)

不使用扩展运算符,但我会使用class而不是函数函数,Object.keys使用{{1}的回调参数生成一个正则表达式(对于所有键) }:

replace
class Template {
    constructor(html) {
        this.html = html;
    }
    resolve(data) {
        const regx = "{{\\s?(" + Object.keys(data).join('|') + ")\\s?}}";
        return this.html.replace(new RegExp(regx, "ig"), (m, prop) => data[prop])
    }
}

const delimiter = '{{ name }}',
    root = document.getElementById('root'),
    html = "<p>My name is {{ name }}</p>",
    tmp = new Template(html);

root.innerHTML = tmp.resolve({
    name: "John Doe"
});

请注意,您应该确保属性are escaped中的任何特殊字符,以便它们不会被<div id="root"></div>解释。但是你没有在你的解决方案中这样做,我也把它排除在外。

相关问题