用node替换html中的值/模板“键”的最佳方法是什么

What is the best way to replace values/template "keys" in html in with node?

本文关键字:最佳 是什么 方法 模板 替换 node html      更新时间:2023-09-26

我想用 node Express 替换 HTML 中的值。例如,

该网页:

<html>
<p> hello {guestName} </p>
</html>

我想替换我的快递应用程序中的{guestName}。 我有一个函数可以获取正确的值,现在该怎么做? 直到现在我都找不到一个好的方法。 谢谢!

模板引擎而言,最接近的东西可能是ejs .

要使用ejs,首先npm install ejs 。然后将此添加到您的 Express 应用代码中:

app.set('view engine', 'ejs');
// this allows you to render .html files as templates in addition to .ejs
app.engine('html', require('ejs').renderFile);

在路由处理程序中,您只需执行以下操作:

res.render('hello', { guestName: 'Foo' });

然后是您的模板(例如 ./views/hello.html ) 将如下所示:

<html>
<p> hello <%= guestName %> </p>
</html>