0

According to the ExpressJS application settings documentation, you should be able to set views as the directory for the view engine. I am experiencing what I think may be a bug; instead of looking in the views directory, express looks in the static directory. Obviously it fails, since it isn't there. I have confirmed this by moving the view into the static directory, and the error goes away.

You can see this bug by cloning this Cloud9 project. I have been unable to confirm this bug outside of Cloud9, (I don't have a linux box available).

The directory structure is simple

project

|-client
  |-assets
  |-views
    |-index.html
|-server.js

here is the server config

var viewDir = __dirname + '/client/views/';
var assetDir = __dirname + '/client/assets/';

//Configure
app.configure(function() {
    app.set('views', viewDir);
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express['static'](assetDir));
    app.use(app.router);
});

app.get('/', function(req, res){        
    res.render('index');
});
Kyeotic
  • 19,697
  • 10
  • 71
  • 128

2 Answers2

4

You need to tell it how to render by setting an engine.

such as an echo:

app.engine('.html', function (file, options, next) {
  fs.readFile(file, function (err, data) {
    if (err) {
      next(err);
    } else {
      next(null, data.toString());
    }
  });
});

You also need to put app.get('/' . . . before app.use(express.static if you want it to take presidence.

You can try it out here: http://runnable.com/UWTRSNJq0z5OAADk

generalhenry
  • 17,227
  • 4
  • 48
  • 63
  • Not long, I'm currently hard at work adding a terminal to it ^_^ – generalhenry Apr 10 '13 at 05:42
  • It looks great. Seems like a nice balance between cloud9 and jsFiddle. Is there any way to actually get it too look for `html` as part of the render, they way it does for other views? If I am using `ejs`, I can use `res.render('index')`, but your method requires me to use `res.render('index.html')`. – Kyeotic Apr 10 '13 at 06:02
  • The express 3.x docs stink on this topic, in short `app.set('view engine', 'html');` `app.engine('.html', require('ejs').__express);` see https://github.com/visionmedia/express/blob/master/examples/ejs/index.js – generalhenry Apr 10 '13 at 06:07
2

Html files are static files whereas files in view have to be rendered by your template engine like jade or ejs. If you want to render html files then check these questions.

  1. Render basic HTML view?
  2. Using express without a template engine

Template engine renders views dynamically. If you have only static pages then you wont need it. But if you have dynamic content, using templates is must.

Community
  • 1
  • 1
user568109
  • 47,225
  • 17
  • 99
  • 123