如何在一个html文件中导航到多个ejs文件而不编写太多代码行



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

HTML

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

server.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。

有没有其他方法可以写它,这样我就不必一遍又一遍地写同样的代码了?

示例:Filename header.ejs:在这个文件中,将您的代码放在header或任何东西上。

现在把这个代码放在任何地方的内容,索引等

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

("…"表示路径名(

你可以像这样在任何地方和任何次数使用它:

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

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

let commands = ['command1', 'command2', 'command3'];
for (let command of commands) {
app.get("/${command}", function (req, res){
res.render(command)
});
}

诚然,这是一种过于简单的方法,如果需要,您可以对此进行详细说明。

最新更新