【问题标题】:pass a variable to ejs将变量传递给 ejs
【发布时间】:2016-03-04 20:48:26
【问题描述】:

我正在尝试将变量传递给 ejs 模板以在浏览器中显示的最简单过程。

我读取了一个只包含一个字符串的文件并将输出分配给一个变量。这很好用,我可以使用 console.log 查看内容。但是,我不知道如何编写 app.get 和 res.render 部分以将该变量发送到 ejs (index.ejs)。

var fs = require('fs');

// Read the contents of the file into memory.
fs.readFile('testfile.txt', function (err, log) {

// If an error occurred, throwing it will
  // display the exception and end our app.
  if (err) throw err;

// log is a Buffer, convert to string.
  var text = log.toString();
        console.log('The content of the log is' + text);
});

// index page
app.get('/', function(req, res) {
    res.render('index', { var:  text }
    });

app.listen(8080);
console.log('8080 port');

谢谢。

【问题讨论】:

  • 问题是readFile()是一个异步方法,所以你的app.get()readFile()之前运行。您可以阅读有关使用异步方法中的值here
  • 附带说明,您不应在传递的对象中使用 var 之类的关键字。此外,您的res.render 上缺少右括号。
  • 感谢您的分析和建议。所以我修复了代码(res.render 上缺少括号)并将其更改为使用下面的同步代码。但是,渲染仍然存在问题。我的 ejs 文件是错误的,但我怀疑它是 res.render: >> 14|

    15|
    16| 17| 文本未定义如何渲染我的“文本”变量并通过 ejs 显示?
  • { var: text } 更改为{ text: text }
  • 标签: node.js ejs


    【解决方案1】:

    您可以使用 nodejs 中的 readFileSync 同步读取文件

        var fs = require('fs');
    
    // Read the contents of the file into memory.
    var text = fs.readFileSync('testfile.txt').toString()
    
    // index page
    app.get('/', function(req, res) {
        res.render('index', { var:  text });
    });
    
    app.listen(8080);
    console.log('8080 port');
    

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多