我如何使我从 nodejs 发送的 ejs 变量工作?

How do i make the ejs variable work that i send from nodejs?

我正在尝试获取一个从 nodejs 发送到 ejs 的变量来工作。但不知为何它不会,我不明白为什么。

这是index.js:

var newOne = "Yes"

router.get('/main', ensureAuthenticated, (req, res) =>
  res.render('main',  {
    user: req.user,
    newOneInView : newOne
  })
)

这是在 main.ejs 文件中:

<%if (newOneInView == "Yes") { %>
  document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
  <% } %>   

所以我想要实现的是,变量将从 main.ejs 页面的 nodejs 中看到,但由于某些原因它不会更改图像 SRC。我在这里做错了什么?

在您的模板中,您需要确保将用于更改 src 属性的代码放置在元素之后的脚本中(或者您可以使用监听器来加载内容) , 例如:

<body>
<img id="avatar" src="/some-other-path"/>
<script>
    <% if (newOneInView === "Yes") { %>
    document.getElementById("avatar").src = "/static/images/Apocaliptic1.png";
    <% } %>
</script>
</body>