Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of Node.js Express registering Underscore.js as view engine?

Underscore.js does not have a compile function like ejs and jade, but does work as a Node.js module. Would someone please provide an example of how to make it work inside an Express app?

like image 539
Jamie Avatar asked Jul 26 '11 04:07

Jamie


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.

What is view engine in Express?

View engines allow us to render web pages using template files. These templates are filled with actual data and served to the client. There are multiple view engines, the most popular of which is Embedded Javascript (EJS).

What is view engine in node?

View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with plain javascript.

What is underscore NPM?

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.


2 Answers

var _ = require('underscore');

app.register('.html', {
  compile: function (str, options) {
    var template = _.template(str);
    return function (locals) {
      return template(locals);
    };
  }
});
like image 190
Jamie Avatar answered Oct 19 '22 01:10

Jamie


Now with express 3.0 , it's a bit different. Easy solution : https://github.com/haraldrudell/uinexpress

npm install uinexpress

then

app.configure(function () {
app.engine('html', require('uinexpress').__express)
app.set('view engine', 'html')
like image 39
Laurent Debricon Avatar answered Oct 19 '22 01:10

Laurent Debricon