Search code examples
templatesgoogle-chromegoogle-chrome-extensionjquery-templates

Chrome Apps. jQuery.Templates analogs


I use jQuery.Template in my chrome app, but few days ago Chrome has updated Chrome Browser and Chrome Web Store and now i can't use manifest_version:1 if I want publish my extension in Web Store. Installation apps from Desktop has been disabled too. So i MUST use manifest_version:2, but there are some troubles with script-src 'unsafe-eval' which were used in jQuery.Templates.

So unsafe-eval is disallowed for script-src directive.

Any suggestions of which JavaScript template engine can be used?

What i need from template engine:

  • No any new Function() or eval() usage.
  • Simple data access like in jQuery.Templates: ${my_variable}
  • Inline logic as: {{if a==b}} ... {{else b == c}} ... {{/if}}
  • May be setting values to variables, but not necessarily: ${my_variable = 123, ''}
  • It must be like a plugin (not framework, i wont to rewrite my app).

Note: No, i wont use sandboxed pages, i think it's very ugly solution.

Upd: thanks for answer. I've choosed Handlebars.js as a main template engine


Solution

  • Big thanks for your detailed answer but i found more elegant solution for me: Handlebars.js.

    It has precompilation engine for templates and doesn't use eval() if using precompiled templates. It has very simple inline logic (I just can check that variable true or false) but it's very fast. =) You should try it for comparison. One moment: it uses NodeJS for precompilation. If you don't need it then just use Handlebars.compile().

    Note: with manifest_version: 2 you MUST use precompilation. If you try to use Handlebars.compile() you'll get error about CSP violation.

    If you have installed NodeJS you may try its precompilation engine using npm install handlebars -g. -g allows you to use handlebars in any project of your FS. You may need sudo this command. Next reload your terminal and cd to folder which consists of template files.

    You need to migrate them to Handlebars.js syntax and add .handlebars extension for each file. Then run handlebars path/to/templates/*.handlebars -f js/templates.js

    If you load this js file after Handlebars.js you should found compiled templates here:

    Handlebars.templates[your_template_file_name]
    

    For example:

    my_template.handlebars

    <div>{{testing_template}}</div>
    

    main.js

    // example with RequreJS
    require(["handlebars", "templates"], function(){
        var template = Handlebars.templates.my_template,
            rendered = template({
                "testing_template" : "some text right here"
            });
    
        console.log(rendered);
    });
    

    In console you'll see this:

    > "<div>some text right here</div>"
    

    Handlebars.js supports simple {{#if}} and {{#unless}} blocks as well as {{#each}} loops and custom helpers. Very powerful as i think.