Reputation: 19804
I'd like to be able to use Underscore.js from within my EJS templates, like this:
<% _.each(articles, function(article){ %>
<section>
<h2><%= title %></h2>
<%= body %>
</section>
<hr/>
<% }) %>
I could inject it for every single route like so...
var _ = require('underscore');
exports.index = function(req, res){
res.render('index', { _: _, articles: app.allArticles() });
};
But that's tedious and prone to human error. Is there a general solution for this, to inject it for all views, all of the time?
Upvotes: 3
Views: 1533
Reputation: 26179
You can do this whith app.locals.
var _ = require('underscore');
var express = require('express');
var app = express();
app.locals._ = _;
// some code
app.listen(3000);
Upvotes: 6