Set 'views' and 'view engine' in the router (Express.js)

Viewed 1440

I am using an Express router to display a completely separate admin interface on a certain path [baseurl]/admin. This interface uses pug as a view engine, so I need to specify the 'views' and 'view engine' settings.

The documentation (https://expressjs.com/en/4x/api.html#app.set) states that: "sub-apps will: - Not inherit the value of settings that have a default value. You must set the value in the sub-app. - Inherit the value of settings with no default value; these are explicitly noted in the table below." It also states that I can think of a router as a "mini-application".

I am currently setting 'views' and 'view engine' in the main app:

app.set('views', 'path/to/views');
app.set('view engine', 'pug');

which works (the router inherits them correctly). However I am wondering how to set them in the router: it should be possible since it's "a sub-app", but there is no router.set(...) method...

2 Answers

I was looking for an answer for the same question, but it seems like you can only set up the engine once for the whole app. As you've mentioned, routers, as subapps, consequently inherit the view settings, moreover, I'm not sure you can create a router without creating the app first. So the answer is - it is not designed to be used like that

I was having the same problem. We cannot set the multiple view engines for the entire application, but you can create the folder "admin" in your views directory and in res.render("admin/login");.

For example, my drectory structure: this is the directory structure

const adminRouter = express.Router();
adminRouter.get("/admin/adminRoute", (req, res) => {
  res.render("admin/login");
})

Related