Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Google Chrome extensions using manifest_version: 2 are restricted from using eval or new Function. All of the JavaScript templating libraries I checked (mustachejs, underscorejs, jQuery template, hoganjs, etc) use new Function. Are there any that are fairly mature and supported that don't use either?

Info about the security restrictions.

like image 808
abraham Avatar asked May 24 '12 20:05

abraham


3 Answers

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

like image 196
zzzzBov Avatar answered Oct 06 '22 13:10

zzzzBov


It turns out that mustachejs added new Function recently and using tag 0.4.2 doesn't have it. It the API is slightly different with Mustache.to_html instead of Mustache.render and there are likely some performance reduction.

I opened an issue to potentially get new Function removed in a future release.

like image 44
abraham Avatar answered Oct 06 '22 12:10

abraham


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

like image 41
Jacob Mattison Avatar answered Oct 06 '22 12:10

Jacob Mattison