【问题标题】:Rendering a variable to ejs template将变量渲染到 ejs 模板
【发布时间】:2016-03-06 03:22:44
【问题描述】:

我正在同步读取文件并将内容发送到变量:

// Load the fs (filesystem) module
 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');

然后在我的 ejs 文件 (index.ejs) 中,我插入了这样的变量:

<main>
        <div class="jumbotron">
            <h2><%= text %></h2>
        </div>
    </main>

我收到“文本”未引用的错误:

>> 14|    <h2><%= text %></h2>
   15|         </div>
   16|     </main>
   17|     </footer>

text is not defined

如何将变量呈现给 ejs?

【问题讨论】:

  • 好吧,我想通了。 :) 我从 text 变量的声明中删除了关键字 var,然后也更改了 res.render 部分: text = fs.readFileSync('testfile.txt').toString() // index page app.get('/ ', function(req, res) { res.render('index', { text }); });

标签: node.js ejs


【解决方案1】:
// Load the fs (filesystem) module
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', { text:  text });
});

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

不要从变量声明中删除 var 关键字,而是在将页面呈现为文本时删除 var 关键字..

它应该可以工作。

【讨论】:

    猜你喜欢
    • 2012-05-08
    • 2016-03-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多