How to pass/access node.js variable to an html file/template ?
The following approach covers how to pass/access node.js variable to an HTML file/template. We will build a basic Node.js application that will let you show dynamic content on an HTML page, i.e. your name and age. For adding the name and age values to our HTML template, we’ll be using the pug package.
Pug is a template engine that can be used to inject dynamic data into an HTML page. Its function is to convert the provided data into HTML content and serve it as a static page. Pug’s syntax resembles that of traditional HTML but is a lot cleaner and prioritizes indentation and spacing for controlling the flow of logic.
Creating NodeJS Application And Installing Module:
Step 1: We can create a new project with Node Package Manager by using the following command.
Step 2: Install the required project dependencies i.e express and pug modules using the following command.
npm install express pug --save
By default, all HTML templates are stored in the views folder in a project. We’ll create the template file index.pug using the same structure.
Project Directory: Our project directory will look like this.
Explanation: The above code it split into 3 sections:
- Importing express and initializing its instance
- Creating a route that will serve the HTML template and also pass data into it (name and age of a user).
- Starting the server.
Explanation: Behind the scenes, the above pub code along with the provided data is translated into an HTML page and then served via the Node.js application.
Step to run the application:
Run the index.js file using the following command.
Output: Now open your browser and go to http://localhost:5000/, you will see the following output: