gpt4 book ai didi

node.js - 嵌入式 JavaScript (EJS) - 从路线动态设置 View

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:42 24 4
gpt4 key购买 nike

我现在正在学习 Nodejs,我的 .ejs 模板文件几乎是标准的(页眉、页脚、js-defaults 等) - 唯一改变它的是 HTML div 中的内容。

我想我可以在我的 route 设置一个变量并将其传递到 View (就像标题或另一个变量一样),然后包含它 - 但它不起作用(下面的示例)。

在 Ruby 中,您可以使用“yield”来完成此操作,我正在尝试使用 EJS 执行相同的操作。

感谢您花时间阅读(请原谅我在这件事上的无知)。

路线示例

app.get('/fish', function(req, res) {

res.render('fish' {
title:"Fish",
template:"view/partials/content/fish.ejs"
});

});

示例 EJS

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<% include views/partials/template/header.ejs %>
<body>
<div class="container">
<!-- Dynamic content here -->
<% include template %> <!-- tries to load template.ejs %>
</div>
</body>
<% include views/partials/template/footer.ejs %>
<% include views/partials/template/js-defaults.ejs %>
</html>

最佳答案

Looks like this is now supported in EJ S.它是在v2.0.1: 2015-01-02中引入的。 。新语法如下所示

 <!-- Dynamic content here -->
<%- include(template) %>

为了使其正常工作,我必须通过设置禁用 Express 中的缓存:

app.set('view cache', false);

关于node.js - 嵌入式 JavaScript (EJS) - 从路线动态设置 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27687463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com