【问题标题】:How to i use the variable from express in html?如何在 html 中使用 express 中的变量?
【发布时间】:2021-07-26 22:34:57
【问题描述】:

我有这个快递

app.get('/', requiresAuth(), (req, res) =>
    res.sendFile('/db_auth_site/index.html', { title: 'Hey', message: 'Hello there!' })
);

如何在 html 中使用标题?

<h1>title variable here</h1>

【问题讨论】:

标签: html node.js express nodejs-server


【解决方案1】:

你本身不能。 HTML 没有这种能力。

您需要使用NunjucksEJSMustache等模板语言。

Express documentation has a section that covers using PugMDN has a more detailed guide

其他模板语言类似,您只需更改您安装的模块和view engine 设置,然后使用您选择的模板语言的语法。

请注意,大多数模板语言都是“您想要输出的语言,其中包含特殊标签”,但 Pug 是一个例外。如果你想写一些看起来像 HTML 的东西,不要使用 Pug。

您还需要使用render 而不是sendFile

【讨论】:

  • Hay sendFile 有效,所以我应该改为发送吗?
  • @Rohit — 当您想发送文件时,它可以工作。当您想将数据注入模板并发送输出时,它不起作用。
  • 哦,好吧,让我看看你发布的链接
  • 我的意思是render,而不是send
  • 哦,好的,我确实发送了,但它给出了一个错误,让我进行渲染
猜你喜欢
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 2018-04-19
相关资源
最近更新 更多