I have a header.html and a footer.html which I would like to be rendered along with other views. I want to accomplish this using Node+Express. I tried to render views in the following way but clearly it doesn't work:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.render('header');
res.render('home');
res.render('footer');
});
You have to set a template engine to your project. You can use Swig for instance, it works very nice and it is well documented.
The example below, shows you how to set it and how you can call partial views from a layout or master page.
Install it by doing npm install swig --save on your project root.
You need to install an additional library called consolidate which acts as interface among different template engine libraries, it is kind of standard in express applications.
npm install consolidate --save
require the library in your main script with
consolidate = require('consolidate');
swig = require('swig');
Configure it as follows:
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views'); // set your view path correctly here
Then you can render a page as:
app.get('/', function (req, res) {
res.render('index', {});
});
(Example taken from Swig's author, Paul Armstrong github page) Layout.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>{% block title %}{% endblock %} - Example</title>
</head>
<body>
<header>
<h1>{% block title %}{% endblock %}</h1>
{% block header %}{% endblock %}
<nav>
<ul>
<li><a href="/">Home Page</a></li>
<li><a href="/people">People</a></li>
</ul>
</nav>
</header>
<section role="main">
{% block body %}{% endblock %}
</section>
</body>
</html>
Index.html:
{% extends 'layout.html' %}
{% block title %}Home Page{% endblock %}
This way, you can decoupled your views as you need :)
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