JavaScript template library that doesn't use eval/new Function

前端 未结 10 1213
抹茶落季
抹茶落季 2021-02-05 17:52

Google Chrome extensions using manifest_version: 2 are restricted from using eval or new Function. All of the JavaScript templating librar

10条回答
  •  别那么骄傲
    2021-02-05 18:18

    It really depends on what you mean by "template library". If you just want string interpolation, there's no need for eval or new Function, when you start needing embedded looping structures, things get more complicated.

    A few months ago I wrote a String.prototype.tmpl.js script that I've used a couple times here and there in places where I don't mind overriding String.prototype. As a static function, you can use:

    tmpl.js:
    function tmpl(tmpl, o) {
        return tmpl.replace(/<%=(?:"([^"]*)"|(.*?))%>/g, function (item, qparam, param) {
            return o[qparam] || o[param];
        });
    }
    
    An example template:

    The base tmpl script can of course be modified to take advantage of document fragments to actually build out DOM elements, but as-is I'm not sure whether it counts as a "template library".

提交回复
热议问题