如何传递/访问node.js变量到html文件/模板



我是新手Node.js和我试图传递和访问一个变量从Node.js加载的html文件/模板,我如何实现这一点?

下面是示例代码:

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');

如何传递和访问名称岁和test.html当我读取文件时,变量的值已经在模板中生成了。

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

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

您可以使用这个库的把手。
这个非常适合处理较大的模板。
如果你必须返回一个标签,你可以试试这个

return `<ul>
<li>Name: ${name}</li>
<li>Age: ${age}</li>
<br>
</ul>`

你也可以考虑为node.js使用这个模板库npm-ejs

最新更新