Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use underscore in jade template

I want to use underscore function in jade template, like this

p= _.keys(user)

Not for client javascript, for in redering.

Through I did require 'underscore' in app.js, did not get along well. Of course it work properly in app.js.

ReferenceError: xxxxxxx _ is not defined

this is template error message. any idea?

thanks

like image 645
dot Avatar asked Dec 06 '11 17:12

dot


People also ask

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. Useful for rendering complicated bits of HTML from JSON data sources.

What is Jade and EJS?

The difference between ejs and jade is that ejs' purpose is to directly add javascript logic and import values to strings of html; Jade is a full templating language with its own syntax. In the end, both compile a template into a javascript function which then glues together the resulting snippets into html.


2 Answers

If you are using Express.js (presumably you would be since you're using Jade) you can add underscore as a view helper.

app.helpers({
    _: require("underscore")
});

UPDATE Using Express 3+, the above will no longer work, use app.locals instead:

app.locals._ = require("underscore");
like image 157
Dominic Barnes Avatar answered Sep 19 '22 16:09

Dominic Barnes


In Express 3.x helpers were removed. Instead use middleware and res.locals

app.use(function(req, res, next){
  res.locals._ = require('underscore');
  next();
});
like image 39
Dave Jensen Avatar answered Sep 19 '22 16:09

Dave Jensen