Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HTML in Express framework with nunjucks- no jade

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.

like image 224
Merlin Avatar asked Nov 11 '13 17:11

Merlin


People also ask

Can you use HTML with Express?

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.

What is view engine in Express?

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).

What is view engine node JS?

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.


1 Answers

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> 
like image 169
robertklep Avatar answered Sep 26 '22 05:09

robertklep