如何在不写太多代码的情况下导航到一个html文件中的多个ejs文件

问题描述 投票:0回答:2

我想导航到 html 文件中的多个 ejs 文件,而不是在 server.js 中编写太多代码行 我安装了 Express 并且隐藏了我的文件扩展名。 这是我的代码。

HTML

<a href = "/contact"> Contact Us </a>
<a href = "/about"> About </a>
<a href = "/pricing"> Pricing </a>

服务器.js

app.get("/contact", function (req, res){
   res.render("contact")
});

app.get("/about", function (req, res){
   res.render("about")
});

app.get("/pricing", function (req, res){
   res.render("pricing")
});

请注意,此方法非常有效

现在,如果我有很多 ejs 文件想要链接到我的 html,该怎么办。

是否有另一种编写方式,这样我就不必一遍又一遍地编写相同的代码?

html node.js express ejs
2个回答
1
投票

您可以指定要处理的命令数组,然后循环它,例如:

let commands = ['command1', 'command2', 'command3'];

for (let command of commands) {
    app.get(`/${command}`, function (req, res){
       res.render(command)
    });
}

这无疑是一种简单化的方法,如果需要,您可以详细说明。


0
投票

示例:文件名 header.ejs:在此文件中,放置标头或任何内容的代码。

现在将此代码放在内容、索引等的任何位置。

<%- include('header'); %>

('...'代表路径名)

您可以在任何地方、任意次数使用它,如下所示:

<div> <%- include('header'); %> </div>
<div> <%- include('header'); %> </div> 
© www.soinside.com 2019 - 2024. All rights reserved.