乐闻世界logo
搜索文章和话题

How to print a variable directly using EJS template engine?

1个答案

1

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:

  1. Setting Express and EJS

    Install Express and EJS:

    bash
    npm install express ejs

    Configure Express to use EJS as the template engine:

    javascript
    const express = require('express'); const app = express(); app.set('view engine', 'ejs');
  2. Creating the EJS Template

    Create a file named profile.ejs in the views directory 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>
  3. Rendering the Template

    In Express, when a request is made to the /profile route, render the profile.ejs template and pass an object containing the username:

    javascript
    app.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.

2024年7月20日 03:48 回复

你的答案