Using Swig templates with ExpressJS
In our last tutorial, we were only outputting strings with res.send. But we want to output HTML page instead. In real-world application, we would use a templating engine like Jade or Swig. Let’s try Swig first.
We set up are expressJS app with the following directory structure.
app.js is the main code that we had written in the last tutorial. Now we added a new folder called “views” and a new file “home.html”. In the home.html file write our basic HTML 5 code for our homepage….
However, we can insert swig template variables there using the double curly braces. And we have done so for the {{title}}. This is a template placeholder where we will be able to pass in dynamic values to this template to display.
Using Swig in ExpressJS
Jumping back to app.js, we added and changed the following code …
Update: app.get(‘*’) is not the best way to handle 404. A better way is to use middleware as shown in this tutorial.
Consolidate is a “template engine consolidation library” that helps us integrate swig templates into Express. We will use this with ..
var cons = require(“consolidate”);
We assign the swig engine to .html files with …
app.engine(‘html’, cons.swig);
We set .html as the default extension …
app.set(‘view engine’, ‘html’);
and tell Express where we can find these htmls …
app.set(‘views’, __dirname + ‘/views’);
__dirname in Express returns the current directory of the current file.
Installing Consolidate and Swig
Since we are using Consolidate, we have to install it via NPM by …
npm install consolidate
npm install swig
Deploy ExpressJS with Swig
Since we had added a bit of stuff, do …
git add .
And …
git commit -m “adding consolidate and swig”
And push to your cloud server (we are using heroku)…
git push heroku master
Visit your app …
See the title in the tab showing “First Swig Template”. That was the value passed to the template. And the view source that was render was the full HTML5 page that we placed in home.html.