Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Access the File System in Node.js ?
Next article icon

How to Pass/Access Node.js Variable to an HTML file/template ?

Last Updated : 26 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When building web applications with Node.js, it’s often necessary to pass server-side variables to the client-side for rendering dynamic content. This can be achieved using various techniques and templating engines. This article will guide you through different methods to pass and access Node.js variables in HTML files or templates.

Approach

We will be using template engines to access the node js variables in html file. Templating engines enable you to embed Node.js variables directly within your HTML. Popular templating engines include EJS, Pug, and Handlebars. Each has its syntax and way of handling data.

Pug

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. 

Installation Steps

Step 1: We can create a new project with Node Package Manager by using the following command.

npm init

Step 2: Install the required project dependencies i.e express and pug modules using the following command.

npm install express pug --save

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2",
"pug": "^3.0.3"
}
HTML
<!-- index.pug -->  doctype html html(lang="en")   head     title= 'Node.js Template'   body     h1 My name is #{name}     p I am #{age} years old 
JavaScript
// index.js   const express = require('express');  // Initialize App const app = express();  // Assign route app.use('/', (req, res, next) => {   res.render('index.pug', { name: 'John Doe', age: 21 }); });  // Start server app.listen(5000, () => {   console.log('App listening on port 5000'); }); 

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 Application: Run the application using the following command from the root directory of the project

node index.js

Output: Now open your browser and go to http://localhost:5000/, you will see the following output:

Visual Representation of index.pug template



Next Article
How to Access the File System in Node.js ?
author
amlankumarnandy
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • NodeJS-Questions

Similar Reads

  • How to make .js variables accessible to .ejs files ?
    EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. It is possible to access JS variable in .ejs file. You just need to pass the JS object as second parameter of res.render() method. Let's jump into deep. Project Structure: Final folder structure will be as
    3 min read
  • How to Access the File System in Node.js ?
    In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
    3 min read
  • How to pass Variable to inline JavaScript using EJS Template Engine?
    In the EJS templating engine, we can pass variables to inline JS within our HTML templates. We can use the '<%= variable %>' syntax, where we can embed server-side variables directly into the client-side scripts. In this article, we will explore the detailed process to pass a variable to inlin
    2 min read
  • How to pass a Node.js variable to the inside of a Pug script tag ?
    In Node.js with Pug, we can pass the variables to the Pug template engine using the res.render method. To make the variable available inside the Pug script tag, we include it in the object passed to res.render and then reference it within the Pug file using the syntax "#{variableName}" inside the sc
    3 min read
  • How to Access Variables from Another File using JavaScript?
    Accessing variables from another file in JavaScript involves exporting the variables from one file and importing them into another. In ES6 modules, use export to share variables and import to access them. In CommonJS (Node.js), use module.exports and require() for the same purpose. Below are the app
    3 min read
  • How to Render a variable as HTML in EJS ?
    In the EJS, the rendering of a variable as HTML consists of a specific tage through which we can control how the content is displayed. This tag involves, <% code %> that allows the execution of code without rendering, <%= code %> escapes and prints the code as HTML, while <%- code %
    3 min read
  • How to load the contents of a text file into a JavaScript variable?
    In this article, we will examine how to read the contents of any text file that exists on your computer into a variable using JavaScript. The following are a few basic pointers that everybody should brush through before looking at the code: Event listeners: These are predefined functions that exist
    3 min read
  • How to Access EJS Variable in Javascript Logic ?
    EJS stands for Embedded JavaScript. It is a templating language used to generate dynamic HTML pages with data from the server by embedding JavaScript code. Features of EJSDynamic Content: Based on data from servers or other sources, we can generate a dynamic HTML template.Partial Templates: Partials
    3 min read
  • How to print a variable directly using EJS template engine?
    EJS (Embedded JavaScript) is a templating engine for NodeJS that enables dynamic content generation in web applications. To print a variable directly in an EJS template, you can use the <%= variable %> syntax. This syntax allows you to embed and display the value of a variable directly within
    2 min read
  • How to Link JavaScript File to a Separate HTML File?
    Linking a JavaScript file to an HTML document establishes a connection between the two, allowing the execution of JavaScript code within the HTML page. This is typically done using the <script> tag in the HTML file, specifying the src attribute as the path to the JavaScript file. Below are the
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences