When setting the view engine in my project; I used this snippet of code and the app works just fine.
// configurations for the view engine
app.set('views', './views');
app.set('view engine', 'pug');
However, I have seen tutorials use a different approach where they attach "__dirName" to it. I am not well versed with express and how it works so I would love to know the functionality of the snippet of the code below. Kindly explain it to me so I can understand the applicability.
// configurations for the view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
CodePudding user response:
these 2 are different things all together..
app.set('view engine', 'pug');is used while setting the view engine. This will set the view template type.app.set('views', path.join(__dirname, 'views'));is used when you have yourpubfiles to be rendered from the backend based on the routes.
Consider the case,
You have your pug files in a below fashion in your directory :
/views/index.pug
/views/about.pug
here views is the folder name and index.pug and about.pug are the files.
you want to render them as for the routes accordingly : / and /about
At that time,
You can use app.set('views', path.join(__dirname, 'views')); so that all your views be rendered from the views folder. ( consider : __dirname, 'views' )
so you can write something like this :
app.get('/', (req,res) => {
res.render('index')
})
app.get('/about', (req,res) => {
res.render('about')
})
so now the code automatically look for index file with the .pug extention present at the location : __dirname, 'views'
Hope this answer helps!! Feel free to comment if you get any doubts and also look at the blogs of express.js..
CodePudding user response:
app.set('view engine', 'pug'); sets pug as the view engine. The code for setting it is the same for both example you provided.
The path that changes (app.set('views', './views');) is the code that tells express what directory to look in for the template files when it renders a view.
__dirname is the directory that the JavaScript module (e.g. server.js) is in. path.join is used to combine it with the string views to give you a subdirectory called views in the directory server.js is in.
If you don't have that, then you have a relative path and it will be computed from the current working directory.
If you were to be in /home/users/you/project/ and type node server.js then it would look for views in /home/users/you/project/views
However, if you were in /home/users/you/ and type node project/server.js then it would look for views in /home/users/you/views (and probably not find them because you would have put them in your project!).
In short, if you don't use __dirname then your code will break depending on what directory you run it from.
Use the __dirname approach.
