使用 ejs 呈现列表项

Rendering a list item using ejs

这是我写的javascript代码

// jshint esversion: 6

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

let items = [];

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));

app.get('/', function(req, res) {
     const today = new Date();

     let options = {
          weekday: 'long',
          day: 'numeric',
          month: 'long'
     };

     let day = today.toLocaleDateString('en-US', options);

     res.render('list', { kindOfDay: day, newListItem: items });
});

app.post('/', function(req, res) {
     let item = req.body.newItem;

     items.push(item);

     res.redirect('/');
});

app.listen(3000, function() {
     console.log('The server started at port 3000');
});

这是我的 ejs 代码

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>To Do List</title>
</head>
<body>

     <h1><%= kindOfDay %></h1>

     <ul>
          <li>Buy Food</li>
          <li>Cook Food</li>
          <li>Eat Food</li>
          <li> <% newListItem %> </li>
     </ul>

     <form action="/" method="post">
          <input type="text" name="newItem">
          <button type="submit" name="button">Add</button>
     </form>
</body>
</html>

问题是,当我启动我的服务器并尝试在列表中添加一个新的列表项时,它没有显示任何错误,但除了通过显示一个点显示一个 li 之外什么也没有显示。

The webpage after entering the list item

问题是你总是渲染 <li></li> 元素,不管你是否真的有 newListItem 或没有(因此空点样式)。仅当存在 newListItem.

时才需要有条件地渲染 li 元素
<ul>
   <li>Buy Food</li>
   <li>Cook Food</li>
   <li>Eat Food</li>
   <%if (newListItem) { %>
      <li> <%= newListItem %> </li>
   <% } %>

</ul>

EJS 是一个非常容易使用的模板框架。您可以随时 google“EJS 条件”、“EJS for 循环”等来查看如何显示您的数据。

只需替换此 <li> <% newListItem %> </li>

用这个<li> <%= newListItem %> </li>

<%=的含义将值输出到模板中(HTML转义)

要通过示例了解有关 EJS 的更多信息,请参阅此 https://ejs.co/