I have been using sendFile method to render Html in Express project. I would like to use partials with my project. And, not switch to jade.
Is there a way to use traditional HTML with partials in Express 3.x. I have tried ejs, but dont understand it completely.
You don't need to install any extra modules to render an HTML file in Express. Just install express and you are good to go.
View engines allow us to render web pages using template files. These templates are filled with actual data and served to the client. There are multiple view engines, the most popular of which is Embedded Javascript (EJS).
View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with plain javascript.
A more 'HTML-like' templating engine would be nunjucks (whose syntax is similar to Jinja2, which you have experience with).
Here's a simple setup. This assumes both Express and Nunjucks are installed, if not:
npm install express npm install nunjucks
– app.js
var nunjucks = require('nunjucks'); var express = require('express'); var app = express(); app.listen(3012); nunjucks.configure('views', { autoescape: true, express : app }); app.get('/', function(req, res) { res.render('index.html', { title : 'My First Nunjucks Page', items : [ { name : 'item #1' }, { name : 'item #2' }, { name : 'item #3' }, { name : 'item #4' }, ] }); });
– views/index.html
<!doctype html> <html> <head> <title>welcome to {{ title }}</title> </head> <body> <ul> {% for item in items %} {% include "item.html" %} {% endfor %} </ul> </body> </html>
– views/item.html
<li>{{ item.name }}</li>
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