Coming from a Rails/Sinatra background, I won't feel at home without being able to use helper functions in my view files, however achieving this in express.js has proven quite difficult.
You can set locals to be automatically included like this...
app.set("name", "Adam's App");
Then in the view file, accessing the variable is as simple as:
<!-- views/template.ejs -->
<title><%= settings.name %></title>
But what about for functions? What if I want to have a date_helper function in my views? I tried setting it like you would a variable...
app.set("date_helper", function(timestamp){ ... });
...however calling <%= settings.date_helper %> won't execute the function (obviously), let alone enable me to pass the timestamp argument to it.
Am I going about this the right way?
You can set view variables at the app level, the response level, and/or at the time of render.
So you could combine these and do something like:
app.locals.date_helper = function(ts) {
return (new Date(ts)).toISOString();
});
app.get('/', function(req, res) {
res.render('main', { timestamp: 1406809421643 });
});
Then inside your template:
The date is: <%= date_helper(timestamp) %>
On a semi-related note, you should be aware of special view variable names used by ejs.