Javascript Template Engines that work with Chrome's Content Security Policy

社会主义新天地 提交于 2019-12-04 00:33:17

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.

You should absolutely use precompilation as recommended by Mathew for medium and big templates. For extremely small templates we are using this:

var template = function(message, data) {
  if (typeof data === 'undefined') {
    return _.partial(template, message);
  } else {
    return message.replace(/\{\{([^}]+)}}/g, function(s, match) {
      var result = data;
      _.each(match.trim().split('.'), function(propertyName) {
        result = result[propertyName]
      });
      return _.escape(result);
    });
  }
};

var data = {
  foo: 'Hello',
  bar: { baz: 'world!' }
};

// print on-the-fly
template('{{foo}}, {{bar.baz}}' args); // -> 'Hello, world!'

// prepare template to invoke later
var pt = template('{{foo}}, {{bar.baz}}');
pt(args); // -> 'Hello, world!'

This implementation does not use eval, but it will require underscore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!