jade template engine Node.js
Jade was a popular template engine for Node.js, but it has been renamed to Pug. Pug is a high-performance template engine that allows you to write concise, readable code. It uses indentation to define the structure of the HTML, and supports advanced features like mixins and filters.
Here's an example of how to use Pug in Node.js:
- Install Pug using npm:
npm install pug
- Create a simple Pug template called
index.pug
:
html head title= pageTitle body h1= pageTitle ul each author in authors li= author
- Create a Node.js file called
app.js
that uses Express to render the template:
const express = require('express') const app = express() const pug = require('pug') const compiledFunction = pug.compileFile('index.pug') const authors = ['Alice', 'Bob', 'Charlie'] const pageTitle = 'My Blog' app.get('/', (req, res) => { res.send(compiledFunction({authors, pageTitle})) }) app.listen(3000, () => { console.log('Server started on port 3000') })
In this example, we first import the pug
module and compile the index.pug
template using pug.compileFile()
. We then define an array of authors and a page title, and use Express to serve the template to the client.
When the client requests the root URL, Express renders the Pug template and sends the resulting HTML to the client.
Note that this is just a simple example - Pug supports a wide range of features, including conditionals, loops, and includes, as well as custom filters and functions. You can refer to the Pug documentation for more information on how to use this powerful template engine.