Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: use underscore along with ejs to render html

I'm currently using EJS templating engine to render my HTML pages, but I want to add underscore to simplify the pre-processing. Right now I do this and it works:

var _ = require("underscore");

app.get('/', function(req, res){
    var data = {};
    data.people = [{ name: "john" }, { name: "marry" }];
    data._ = _; // inject underscore.js
    res.render('index', data);
});

Now to render the HTML I have access to underscore:

<% _.each(people, function(person){ %>
    <div><%= person.name %></div>
<% }); %>

However, I have to inject underscore for every route, is there a way to always inject underscore? (maybe somewhere in app.engine setting ?)

like image 301
Maria Avatar asked May 02 '15 08:05

Maria


People also ask

What is the use of underscore in node JS?

Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.

Why we use _ in JS?

Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.


1 Answers

You could bind _ to app.locals.

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

app.locals._ = _;

app.get('/', function(req, res){
    var data = {};
    data.people = [{ name: 'john' }, { name: 'marry' }];
    res.render('index', data);
});

In your view:

<% _.each(people, function(person){ %>
    <div><%= person.name %></div>
<% }); %>

There is a great answer from another SO user: Access req and res inside of app.locals

See the documentation on app.locals vs. req.locals

I just added quotes around the names 'john' and 'marry'

like image 54
roland Avatar answered Nov 03 '22 01:11

roland