【问题标题】:How to pass/access node.js variable to an html file/template如何将 node.js 变量传递/访问到 html 文件/模板
【发布时间】:2021-05-25 10:59:30
【问题描述】:

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

【问题讨论】:

    标签: javascript html node.js fs


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      您也可以考虑将这个模板库用于 node.js npm-ejs

      【讨论】:

      • 嗨@Omkar,非常感谢。我使用ejs 让它工作。
      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 2016-10-25
      • 2014-02-09
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      相关资源
      最近更新 更多