Outputting variables in the EJS template engine is a fundamental and common operation. EJS integrates data with templates to generate HTML content, which is highly useful for Server-Side Rendering (SSR) applications.
Basic Syntax
In EJS, to directly display the value of a variable within an HTML template, you can use the <%= %> tag. This tag evaluates the JavaScript expression inside it, converts the result to a string, and inserts it into the rendered output. For example:
ejs<p>Username: <%= username %></p>
In this example, username is a variable whose value is directly inserted into the <p> tag.
Example
Let's consider a simple Express.js server where we want to render a page using the EJS template engine to display the user's name. We can set it up as follows:
-
Setting Express and EJS
Install Express and EJS:
bashnpm install express ejsConfigure Express to use EJS as the template engine:
javascriptconst express = require('express'); const app = express(); app.set('view engine', 'ejs'); -
Creating the EJS Template
Create a file named
profile.ejsin theviewsdirectory of your project with the following content:ejs<!DOCTYPE html> <html> <head> <title>User Profile</title> </head> <body> <h1>Welcome to your profile!</h1> <p>Username: <%= username %></p> </body> </html> -
Rendering the Template
In Express, when a request is made to the
/profileroute, render theprofile.ejstemplate and pass an object containing the username:javascriptapp.get('/profile', (req, res) => { res.render('profile', { username: '张三' }); });Here, when a user accesses
/profile, they will see a page displaying 'Username: 张三'.
Summary
Using the <%= %> tag, EJS enables direct output of JavaScript variables within HTML templates. This simplifies the dynamic generation of content based on user data. In real-world projects, this method can be used to display user information, article content, and dynamic table data.