首页 > 解决方案 > 如何将 node.js 变量传递/访问到 html 文件/模板

问题描述

我是Node.js的新手,我正在尝试将一个变量从Node.js传递和访问到加载的html文件/模板,我该如何实现?

这是示例代码:

测试.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>

我的服务.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模板,以便在读取文件时,变量的值已经在模板中生成。

标签: javascripthtmlnode.jsfs

解决方案


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

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


推荐阅读