Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Node.js know to render ejs in views folder

Tags:

node.js

I am currently new and learning Node.js and web development in general, and in a route when I render an ejs file, the code would be something like: res.render("index").

Index.ejs would be in a folder called views. How does Node know to look into my views subfolder ( from the project/ parent folder)?

like image 599
Bri Expost Avatar asked Oct 25 '25 03:10

Bri Expost


2 Answers

It depends on what nodejs framework you are using. If you are using expressjs framework then you can tell your app.js the location of the views folder by doing the following.

//in app.js

app.set('views', config.root + '/app/views')
app.set('view engine', 'jade')

And the views can then be rendered in the routes.js file like this.

// in routes.js
module.exports = function (app) {
  // home route
  app.get('/', home.index)
}
like image 193
Muje Avatar answered Oct 26 '25 18:10

Muje


In Node, there is something called Template Engine. A template engine enables you to use static template files in your application at runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client

If you are using express js you can first set the view engine like this

app.set('view engine', 'ejs')

And then in your routes, you can do like this

app.get('/new.html', function(req,res) {
    res.render('new.html');
});

Note that the template engines that work with Express are Pug, Mustache, and EJS. The Express application generator uses Jade as its default, but it also supports several others.

like image 35
Hadi Mir Avatar answered Oct 26 '25 16:10

Hadi Mir