📖 Scenario: You are building a simple Express web server that uses EJS templates to render HTML pages dynamically.This project will guide you through setting up EJS as the view engine and creating a basic template.
🎯 Goal: Set up an Express app to use EJS templates and create a simple EJS file that displays a greeting message.
📋 What You'll Learn
Create an Express app instance
Set EJS as the view engine
Create a views folder with an EJS template file
Render the EJS template from a route
💡 Why This Matters
🌍 Real World
Web developers use EJS templates with Express to create dynamic web pages that change based on data or user input.
💼 Career
Knowing how to set up and use EJS with Express is a common skill required for backend web development jobs using Node.js.
Progress0 / 4 steps
1
Create Express app instance
Write code to import express and create a variable called app by calling express().
Express
Hint
Use require('express') to import Express and then call it to create the app.
2
Set EJS as the view engine
Add code to set the view engine of app to 'ejs' using app.set('view engine', 'ejs').
Express
Hint
Use app.set method to specify the view engine as 'ejs'.
3
Create EJS template file
Create a file named index.ejs inside a folder called views. Inside index.ejs, write HTML code with a <h1> tag that displays the text Hello, EJS!.
Express
Hint
Inside the views folder, create index.ejs with a simple <h1> tag containing Hello, EJS!.
4
Render EJS template from route
Add a route handler for GET requests to '/' on app that calls res.render('index') to render the index.ejs template.
Express
Hint
Use app.get to create a route for '/' and call res.render('index') inside the handler.
Practice
(1/5)
1. What does the line app.set('view engine', 'ejs') do in an Express app?
easy
A. It creates a new EJS file in the views folder.
B. It installs the EJS package automatically.
C. It tells Express to use EJS as the template engine for rendering views.
D. It starts the Express server with EJS support.
Solution
Step 1: Understand the purpose of app.set
This method configures Express settings, here it sets the template engine.
Step 2: Identify what 'view engine' setting does
Setting 'view engine' to 'ejs' tells Express to use EJS to render view files automatically.
Final Answer:
It tells Express to use EJS as the template engine for rendering views. -> Option C