Introduction:
Node.js Jade is a templating engine that allows developers to write dynamic HTML templates in a concise and expressive manner. It was previously known as "Jade" but later renamed to "Pug" to avoid trademark conflicts. However, for the purpose of this documentation, we will refer to it as Node.js Jade.
Installation:
To use Node.js Jade in your Node.js project, you need to install it using npm (Node Package Manager). Open your terminal and run the following command:
bashnpm install jade
Usage:
- Include Jade:
Before using Jade in your Node.js application, you need to require it at the beginning of your script.
javascriptconst jade = require('jade');
- Compile Jade Template:
You can use thejade.compile()
method to compile Jade templates into a reusable function.
javascriptconst jadeTemplate = `
doctype html
html
head
title= pageTitle
body
h1= greeting
p Welcome to #{location}
`;
const compiledFunction = jade.compile(jadeTemplate);
- Render HTML:
Once you have the compiled function, you can render the HTML by passing data as an argument to the function.
javascriptconst data = {
pageTitle: 'ChatGPT Documentation',
greeting: 'Hello, User!',
location: 'ChatGPT App'
};
const htmlOutput = compiledFunction(data);
- Display Output:
You can use the rendered HTML output as per your needs, such as sending it as a response to an HTTP request or rendering it in a view.
javascriptconsole.log(htmlOutput);
Explanation:
In the above example, we start by requiring the jade
module using const jade = require('jade');
. Then, we define a Jade template using the jadeTemplate
variable, containing a simple HTML structure with variables denoted by #{}
. The compiledFunction
is created using jade.compile()
, which returns a function capable of rendering the HTML based on the provided data.
After that, we prepare a data
object containing values for the variables used in the template. When calling the compiledFunction(data)
, it substitutes the variables with the corresponding values and returns the final HTML output. In this example, we log the output to the console, but you can integrate it into your Node.js application according to your requirements.
Please note that Jade's syntax is indentation-based, so it's crucial to maintain correct indentation for nested elements.
For more complex templates and features, you can explore the official documentation and examples available on the Node.js Jade/Pug website.
0 Comments