Jonathan Ong
Jonathan Ong

Reputation: 20315

Jade not finding view in different folder

I have a directory like this

/Workspace
  /app
    app.js
  /lib
    /public
      /styles
        *.css
      /scripts
        *.js
    /views
      *.jade

from app.js in app, I have the following code:

libPath = __dirname + '/../lib'

... express stuff ...

app.configure(function() {
  app.set('view', libPath + '/views')
  ... express stuff ...
  app.use(express.static(libPath + '/public'))

... rest of the app ...

Now, the problem is that Jade can't find any of the views, but all the static assets are found. Thus, app.set('view') isn't working, but express.static is. If I copy the views directory to app, using __dirname + '/views' works fine. Anyone know why this is happening?

doing app.get('view'), I get a directory like this: /Users/jong/Workspace/app/../lib/views. I tried doing the absolute route /Users/jong/Workspace/lib/views as well to no avail. It's just weird that this directory works for static assets but not templates.

Upvotes: 1

Views: 2076

Answers (1)

penartur
penartur

Reputation: 9912

You have a mistype, the correct option name is views, not view.

Configure your application like

    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.set('view options', { layout: true });

But the main root of issue is that you seem to misunderstand how express (and the MVC at all) works.

express sends out the static data to the browser, using your express.static configure directive, once the request url matches the existing static file path.

Otherwise, it tries to find any defined route for the requested path and to execute the associated controller (which may or may not use the template engine in turn).

So, in order to show e.g. the index page (even if it has no parameters), given you have an index.js in your views folder, you have to do something like

app.get('/', function (req, res, next) {
    res.render('index', {});
});

Upvotes: 5

Related Questions