Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 443
deltanovember Avatar asked Apr 23 '12 14:04

deltanovember


People also ask

How do you use underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

What is underscore template?

The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering.


3 Answers

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 {{ }}.

like image 172
Robert Peters Avatar answered Oct 22 '22 06:10

Robert Peters


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().

like image 33
Marc Avatar answered Oct 22 '22 05:10

Marc


I had the same issue when I wanted to render the webpage using ejs template on back-end (express), meanwhile I had to use underscore template on front-end.

I tried Marc's answer but it doesn't help, I think it has been out of date to use in newer version. In newer version of ejs(mine is 2.3.3), you can no longer use ejs.open and ejs.close, use ejs.delimiter instead.

I changed the delimiter to '$' in ejs so ejs would only handle with <$ $> tag to insert variables and take <% %> tag as meaningless syntax.

app.set('view engine', 'ejs');
var ejs = require('ejs');
ejs.delimiter = '$';
app.engine('ejs', ejs.renderFile);

NOTE: I add the code above in app.js file in express applications and it worked fine, and if you want to use it on front-end, just pass {'delimiter': '$'} in ejs.render(str, options) as options argument.

like image 20
myan Avatar answered Oct 22 '22 06:10

myan