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

前端 未结 10 1210
抹茶落季
抹茶落季 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:
    <div id="bar"></div>
    <script type="text/x-tmpl" id="foo">
        <h1><%=title%></h1>
        <p><%=body%></p>
    </script>
    <script>
        (function () {
            var foo,
                bar;
            foo = document.getElementById('foo');
            bar = document.getElementById('bar');
            bar.innerHTML = tmpl(foo.innerHTML, {
                title: 'foo bar baz',
                body: 'lorem ipsum dolor sit amet'
            });
        }());
    </script>
    

    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".

    0 讨论(0)
  • 2021-02-05 18:24

    It doesn't appear that Pure uses either eval or new Function.

    0 讨论(0)
  • 2021-02-05 18:25

    The answers here are outdated so I post an update.

    Since September, Google changed their policy and allowed unsafe-eval in manifest 2 extensions. See this thread and this page.

    So libraries using eval(), new Function() etc. can be used if unsafe-eval is turned on for your extensions.

    0 讨论(0)
  • 2021-02-05 18:29

    Distal template doesn't use eval.

    0 讨论(0)
  • 2021-02-05 18:30

    The best solution to this problem is to pre-compile your templates before you deploy your extension. Both handlebarsjs and eco offer pre-compilation as a feature. I actually wrote a blog post that goes into more depth.

    0 讨论(0)
  • 2021-02-05 18:34

    I recently run into the same problem. After updating manifest version my extension stopped working. I tried Mustache but it unable to render index of the array and names of the object properties. So I had to create my own simple but effective templating library Ashe which is free of eval and new Function. Hope it will help someone.

    0 讨论(0)
提交回复
热议问题