سؤال

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?

هل كانت مفيدة؟

المحلول

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
});

نصائح أخرى

I assume the question could be read as following in an uncontextualised case.

“How I can escape EJS template code delimiter tag only for limited item?”

tl;dr:

Use <%# %> to break the original parsing code (e.g. <<%# %>%= done ? 'done' : '' %<%# %>> will done the following unparsed code <%= done ? 'done' : '' %>)

Long explanation

Imagine a case I decide to change % by ? using { delimiter: '?' } option.

Great, that solves your problem. Imagine now later, for some reason, you use your templating system to generate an XML. This XML will start with <?xml version="1.0" encoding="UTF-8"?>.

And you will have the same issue, again. What do? You will change the delimiter again? And after that, you will change again? etc. No, for punctual escaping, what we should is just to be capable to say “Not parse this part of the document as EJS”.

So a trick is to avoid EJS understand it's an EJS delimiter parser. So avoid it (in our current case) parse <? (or <% in an original case).

So by simply adding <?# ?> to break the parsing, you will add nothing (the # item is for EJS comment) and you will avoid parser to understand <<?# ?>?xml version="1.0" encoding="UTF-8"?<?# ?>>. The output will be <?xml version="1.0" encoding="UTF-8"?>

Conclusion

In a punctual necessity to avoid EJS parsing, you can just trick the parser to produce the output you need by using <%# %> as a delimiter tag breaker.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top