Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

app.set('views', __dirname + '/views') in Express & node.js

I'm confused with the app.set() method. As far as I know, app.set() is like this

app.get('title');
// => undefined

app.set('title', 'My Site');
app.get('title');
// => "My Site"

but in tutorials, make 'views' folder and use like this.

app.set('views', __dirname + '/views')
app.get('/') or app.get('/admin')

shouldn't it be like this?

app.get(views)
like image 443
KimCrab Avatar asked Apr 30 '15 07:04

KimCrab


People also ask

What is app set views?

The views is a configuration variable that sets folder from which express will grab templates. app. get('/admin') also differs from app. get('variable') . First is a GET route, that would listen HTTP Server, the second is just environment variable of express.

What is App Express ()?

=> Calls the express function "express()" and puts new Express application inside the app variable (to start a new Express application). It's something like you are creating an object of a class.


2 Answers

app.set(name, value)

Assigns setting name to value, where name is one of the properties from the app settings table.

views

Type:String or Array

A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.

app.set('views', path.join(__dirname, 'views')); 

This will set your apps view folder to something like:

/Users/adil/Project/myApp/views

When you actually go to use the view, the view name becomes the file path, minus the root directory and the file extension. For example, if you had the following file structure:

/views/
/views/index.hbs
/views/news/
/views/news/index.hbs
/views/news/article1.hbs
/views/news/article2.hbs

You would render the views as follows:

res.render('index', {});  
res.render('news/index', {});  
res.render('news/article1', {});  
res.render('news/article2', {});
like image 60
Adiii Avatar answered Oct 21 '22 23:10

Adiii


The views is a configuration variable that sets folder from which express will grab templates. app.get('/admin') also differs from app.get('variable'). First is a GET route, that would listen HTTP Server, the second is just environment variable of express.

like image 22
vanadium23 Avatar answered Oct 21 '22 23:10

vanadium23