mpen
mpen

Reputation: 283313

How to include server-side script in Jade template?

I've just installed moment.js; now I want to access moment inside my Jade template. Example:

.main-content
    .container
        .access-details.clearfix
            .left
                div Logged in: <b>#{user.name}</b>
                div Access Lvl: #{user.accessLevel}
            .right
                div= moment().format("dddd, MMMM Do YYYY, h:mm:ss a")

To be clear, I want the date to be formatted server-side and then sent to the client as a rendered string.

So how do I make a JavaScript library available inside of a Jade template?


I should probably note that I'm using this with Express:

var server = express.createServer();
server.configure(function () {
    server.set('view engine', 'jade');

Is there some options I have to pass in there somehow to tell it which libraries to include?


Just occured to me that this is absolutely no different than passing in a local variable. e.g.,

server.get('/', function (req, res) {
    res.render('index', {
        locals: {
            moment: require('moment')
        }
    });
});

But I don't want to pass this in to every view; if I ever forgot it my app would break as it's used in the main layout. So how do I make sure it's always available?

Upvotes: 15

Views: 5102

Answers (2)

lijinma
lijinma

Reputation: 2942

Helpers are removed from Express 3 or 4.

Kindly use app.locals

app.locals.moment = require('moment');

The app.locals object is a JavaScript Object. The properties added to it will be exposed as local variables within the application.

So you can use app.locals in any view files, Jade or EJS;

moment().format('YYYY-MM-DD h:mm:ss');

Upvotes: 20

mpen
mpen

Reputation: 283313

This answer got my pointed in the right direction, although the documentation on dynamicHelpers seems to have mysteriously disappeared from the Express documentation.

Also, I didn't need a dynamic helper, just a static one (no access to request/response). So I took a stab in the dark at what it would be called:

server.helpers({
    moment: require('moment')
});

Works like a charm! moment is now available in all my views.

Upvotes: 8

Related Questions