Introduction to Consolidate.js: A Powerful Templating Engine for Node.js
Consolidate.js is a popular library in the Node.js ecosystem, providing a unified API for a plethora of templating engines. This allows developers to quickly and efficiently switch between different templating engines with minimal code changes. In this article, we’ll explore the core functionalities of Consolidate.js and provide several useful API examples to help you harness its power.
Installing Consolidate.js
npm install consolidate
npm install ejs // Example templating engine
Basic Usage with EJS
Here’s a straightforward example of using Consolidate.js with the EJS templating engine:
const consolidate = require('consolidate');
const path = require('path');
const fs = require('fs');
// Render EJS template
consolidate.ejs('views/template.ejs', { name: 'John' })
.then(html => {
console.log(html);
});
Using Promises with Consolidate.js
Consolidate.js also supports promise-based rendering, making it easier to work within an async/await environment:
const renderTemplate = async () => {
const html = await consolidate.ejs('views/template.ejs', { name: 'John' });
console.log(html);
};
renderTemplate();
Using Handlebars with Consolidate.js
Switching to another templating engine, such as Handlebars, is straightforward with Consolidate.js:
const consolidate = require('consolidate');
const path = require('path');
const fs = require('fs');
// Render Handlebars template
consolidate.handlebars('views/template.hbs', { title: 'My Blog' })
.then(html => {
console.log(html);
});
Using Pug with Consolidate.js
const consolidate = require('consolidate');
const path = require('path');
const fs = require('fs');
// Render Pug template
consolidate.pug('views/template.pug', { user: 'Alice' })
.then(html => {
console.log(html);
});
Handling Errors in Consolidate.js
Consolidate.js makes it simple to handle errors during rendering:
consolidate.ejs('views/template.ejs', { name: 'John' })
.then(html => {
console.log(html);
})
.catch(err => {
console.error('An error occurred:', err);
});
Complete Express Application Example
Here is a complete Express application demonstrating the use of Consolidate.js with a variety of templating engines:
const express = require('express');
const consolidate = require('consolidate');
const app = express();
const port = 3000;
app.engine('html', consolidate.swig);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.get('/', function (req, res) {
res.render('index', { title: 'Consolidate.js Example' });
});
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
By leveraging Consolidate.js, you can significantly streamline the use of various templating engines within your Node.js applications. Switch engines effortlessly and maintain cleaner code with this robust utility!
Hash: 291cf1ed742e8a354179069c9f31bff1d23de7bfe328d86cbc4f81a2c8d067e8