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)?
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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With