underscore.jstemplatingejsunderscore.js-templating

Outputting an underscore template in EJS


I would like to mark a block of text inside an EJS template not to be touched by EJS during output generation. This block contains "EJS" tags because it is an underscore.js template which uses the same syntax.

Can I do this without changing the delimiters of either of the templating engines?


Solution

  • Don't do that, You'll be asking for a world of hurt when your future self comes back to this.

    There isn't an escape for "ejs" like your asking but there are some close alternatives.

    1. Use String.replace to make your own escape syntax.
    2. Modify the underscore delimiters (which can be done on a one off basis).
    3. Split the two template into separate concerns to avoid embedding templates inside a template.

    replace

    var template = _.template('<%= $.a %> foo #%= something_else %>',
      null, {variable: '$'});
    var ejs = template({a: 'bar'}).replace(/#%/g, '<%');
    

    modify delimiters

    var template = _.template('{{ $.a }} foo <%= something_else %>',
      null, {
        variable: '$',
        interpolate: /\{\{(.+?)\}\}/g
      });
    var ejs = template({a: 'bar'});
    

    separate concerns

    var ejs_template = '<%= something_else %>';
    var template = _.template('<%= $.a %> foo <%= $.ejs %>',
      null, {variable: '$'});
    var ejs = template({
      a: 'bar',
      ejs: ejs_template
    });