0

I am building out a MEAN app right now that is getting big. I really need to start modularizing the app but right now my Express server is configured to look for Jade views in one folder

app.set('views', path.join(__dirname, '/app/views'));
app.set('view engine', 'jade');

The authors of these posts show the view files scattered about the app in the different module directories.

If I try to do this now, my Express server will not be able to see them. How can I make it so Express will be able to find all the Jade views?

2 Answers2

0

Two solutions :

  • You can use a base folder named views and create subfolders inside views. For example, views/menu/, views/header/. To use this, you have to declare a basedir in Express so Jade will know where to look your views, by doing app.locals.basedir = __dirname + "/views";. Then, in your Jade file, use include /header/a.jade, include /menu/item1.jade etc...
  • Use Express App submounting feature. This allows you to modularize your main app into small apps, which all have their own routes, views etc... You can watch this nice video tutorial by TJ Holowaychuk to learn more about this.

Does that help you ?

Waldo Jeffers
  • 2,289
  • 1
  • 15
  • 19
  • I decided to go with the Express submounting feature which works fine. I still don't fully understand how it works with the whole circular dependency thing as talked about in this SO answer http://stackoverflow.com/a/21103523/883807 but I'll figure it out eventually. Thanks Waldo :) –  Aug 23 '14 at 10:44
0

I just start using module prefixes in my render calls and set my views base directory to be the parent directory of my modules. So if I started with:

app/views/page1.jade
app/views/page2.jade

and was doing res.render("page1"), I reorganize to:

app/module1/page1.jade
app/module2/page2.jade

and I do app.set("views", "app") then render with res.render("module1/page1").

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • I created around 20 different module folders for my app with controllers, views and a module.js file in each. So you are saying for each of these folders I will have to do a `res.render()` on it to be able to render the view? e.g. for the signup module, `res.render("signup/signup")` in which the first `signup` in the path refers to the module folder and the second `signup` in the path refers to `signup.jade` –  Aug 18 '14 at 12:31
  • Yes, that's right. Of course, if you have a lot of pages and this becomes a clear pattern, you can extract a middleware that will automatically render the correct template based on the URL path if you like. I often don't have a 1-1 mapping of URL paths to template paths though. – Peter Lyons Aug 18 '14 at 17:25