导入
用于动态内容的模板引擎
探索在 Express 中使用 EJS 和 Pug 等模板引擎,通过服务器端数据动态渲染 HTML 页面。
...
模板引擎处理过程
1const express = require('express'); 2const app = express(); 3 4app.set('view engine', 'ejs'); 5app.set('views', './views');
1app.get('/', (req, res) => { 2 res.render('index', { title: 'Home', message: 'Welcome to Express with EJS!' }); 3});
1<!DOCTYPE html> 2<html> 3 <head> 4 <title><%= title %></title> 5 </head> 6 <body> 7 <h1><%= message %></h1> 8 </body> 9</html>
1app.get('/', (req, res) => { 2 res.render('index', { title: 'Home', message: 'Welcome to Express with Pug!' }); 3});
1doctype html 2html 3 head 4 title= title 5 body 6 h1= message
1<!-- views/partials/header.ejs --> 2<header> 3 <h1>My Site</h1> 4</header>
1<!-- views/index.ejs --> 2<%- include('partials/header') %> 3<h2>Welcome</h2>
1//- views/partials/header.pug 2header 3 h1 My Site
1//- views/index.pug 2include partials/header 3h2 Welcome
1app.get('/users', (req, res) => { 2 const users = ['Alice', 'Bob', 'Charlie']; 3 res.render('users', { users }); 4});
1<ul> 2 <% users.forEach(user => { %> 3 <li><%= user %></li> 4 <% }) %> 5</ul>
1ul 2 each user in users 3 li= user
No configuration found for ID: d37bb725fea485ee88163362de295d192f67150ba1d21c302ba15178201a1fae
...
1 / 4
http://localhost:3000/
1const users = [ 2 { name: 'Jane Doe', age: 28, location: 'New York' }, 3 { name: 'John Smith', age: 35, location: 'San Francisco' } 4];
No configuration found for ID: 8eed7babd8f3109d276b35c216e69f56e2f1e66ccf7f1c993b70b45ef28bc646
...
预期输出:渲染动态用户档案
解决方案
解决方案
在 server.js 中按如下方式定义 /profiles 路由:
/profiles 路由的解决方案
1app.get('/profiles', (req, res) => { 2 const users = [ 3 { name: 'Jane Doe', age: 28, location: 'New York' }, 4 { name: 'John Smith', age: 35, location: 'San Francisco' } 5 ]; 6 res.render('profiles', { users }); 7});
说明:
第2–5行:创建一个用户对象数组,每个对象包含姓名、年龄和所在城市。
第6行:渲染
profiles.ejs模板,并将users数组传递给该模板。
更新 profiles.ejs 文件如下:
profiles.ejs 文件内容
1<!DOCTYPE html> 2<html> 3 <head> 4 <title>User Profiles</title> 5 </head> 6 <body> 7 <h1>User Profiles</h1> 8 <ul> 9 <% users.forEach(user => { %> 10 <li> 11 <strong>Name:</strong> <%= user.name %><br> 12 <strong>Age:</strong> <%= user.age %><br> 13 <strong>Location:</strong> <%= user.location %> 14 </li> 15 <% }) %> 16 </ul> 17 </body> 18</html>
说明:
第9行:遍历
users数组。第10–14行:每个
<li>元素通过<%= %>插入用户的姓名、年龄和所在地信息。第15行:
<% }) %>结束循环。