javascript - 如何将 Node.js 变量传递/访问到 html 文件/模板

标签 javascript html node.js fs

我是 Node.js 新手,我正在尝试将变量从 Node.js 传递并访问到已加载的 html 文件/template,我该如何实现这一目标?

这里是示例代码:

test.html

<!DOCTYPE html>
<html>
    <head>
        <mate charest="utf-8" />
        <title>Hello world!</title>
    </head>
    <body>
        <h1>User List</h1>
        <ul>
            <li>Name: Name</li> <!-- how do I call the name variable here -->
            <li>Age: Age</li> <!-- how do I call the age variable here -->
            <br>
        </ul>
    </body>
</html>

myService.js

let fs = require('fs');
let path = require('path');

// How do I pass this variables to test.html
let age = 1;
let name = "this is name";

// Read HTML Template
let html = fs.readFileSync(path.resolve(__dirname, "../core/pdf/test.html"), 'utf8');

如何将nameage变量传递并访问test.html模板,以便在读取文件时,值变量的值已在模板中生成。

最佳答案

为此,您需要使用 Express 和模板引擎。请参阅模板引擎列表 - https://expressjs.com/en/resources/template-engines.html

https://expressjs.com/en/starter/generator.html

关于javascript - 如何将 Node.js 变量传递/访问到 html 文件/模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66328620/

相关文章:

javascript - 带有自定义元素符号的自动图像 slider

JavaScript 到 PHP 的转换

javascript - 如何通过javascript访问响应数据索引

html - 媒体查询规则不会覆盖原始规则

javascript - Safari 浏览器上的强制“另存为”对话框

node.js - 生成配置模板时如何处理依赖项安装?

javascript - 来自终端的 npm install 错误

node.js - 如何在 Yeoman Ember 应用程序中设置/获取环境特定变量

javascript - 使用 Javascript 在 forEach 中进行切换是不好的做法吗?

javascript - 还使用 jQuery 时如何处理 Javascript 错误?