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

后端 未结 2 1033
深忆病人
深忆病人 2021-02-19 15:48

The Chrome API\'s Manifest version 2 has removed the ability to do unsafe-eval. This means using the eval function or in general dynamically creating a function from text.

2条回答
  •  灰色年华
    2021-02-19 16:24

    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.

提交回复
热议问题