首页 > 解决方案 > 如何正确评估 EJS IF/ELSE

问题描述

我的变量 'answer' 作为字符串 'success' 返回,并正确打印到视图中。

但是 IF/ELSE 语句总是对 ELSE 进行评估并显示“否”而不是“是”。我究竟做错了什么?谢谢!

<h3><%= answer %> </h3>
<% if (answer == 'success') { %>
   <p>yes</p>
<% } else { %>
   <p> no</p>
<% } %>

标签: javascriptnode.jsejs

解决方案


您确定正确发送成功的价值吗?这是我所做的并得到了预期的yes.

index.js

const express = require('express');

const app = express();
const port = process.env.PORT || 3000;


app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.render("test", {answer: 'success'});
});

app.listen(port, () => {
  console.log(`listening on port ${ port }`);
});

测试.ejs

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
    <h3><%= answer %> </h3>
    <% if (answer == 'success') { %>
       <p>yes</p>
    <% } else { %>
       <p> no</p>
    <% } %>
</body>
</html>

和结果

在此处输入图像描述


推荐阅读