How can I use Underscore.js templates in conjunction with EJS?

They both use the same syntax for inserting variables. For example if I want the following

<%= username %>

In my Underscore, my main EJS breaks because it tries to replace username and no such variable exists in the main page.

I had this issue and thought I would share the solution I found for solving the issue client side. Here is how your change the escape regex (via underscore.js docs):

_.templateSettings = {
    interpolate : /\{\{(.+?)\}\}/g
};
var template = _.template( "{{example_value}}");

Changes the <%= %> to {{ }}.

I think square brackets will work in EJS by default:

[%= username %]

And if you need to get fancier, the EJS github page describes how to create custom tags:

var ejs = require('ejs');
ejs.open = '{{';
ejs.close = '}}';
  • I think that 2nd "fancier" part might be specific to server-side applications

https://github.com/visionmedia/ejs

Using the client side GitHub example, you'd need to do syntax like this when you render:

var html = require('ejs').render(users, { open: "^%", close: "%^" });

Options are the 2nd parameter of the render().