如何在html文件中呈现数组? - Node.js,ejs

时间:2021-12-24 18:58:45

I'm working on a project, which will use given coordinates from a txt file and graph them. My problem right now: I'm trying to use ejs to render the coordinates into my html file, but it just isn't working right. Ejs always just renders: undefined.

我正在研究一个项目,该项目将使用来自txt文件的给定坐标并绘制图形。我现在的问题是:我正在尝试使用ejs将坐标渲染到我的html文件中,但它只是不能正常工作。 Ejs总是只渲染:未定义。

Here is the code:

这是代码:

var http = require('http'),  
    fs = require('fs'),
    express = require('express'), 
    app     = express(); 
    app.use(express.bodyParser());
    app.set('view engine', 'ejs');
    app.engine('html', require('ejs').renderFile); 
    app.use(express.static(__dirname + '/public'));

//Readerfunction 
function readLines(input, done) {
   //..... 

function done(arr) { 
    var obj = {};
    var key1 = arr[0][0];
    var key2 = arr[0][1];
    obj[key1] = [];
    obj[key2] = [];

    arr.shift();

    arr.forEach(function (item) {
        obj[key1].push(item[0]);
        obj[key2].push(item[1]);
    });

      console.log('X:', obj[key1]); // all the variables are logged correctly. 
      console.log('Y:', obj[key2]); 

    app.get('/', function(req, res) {   
          res.render('graph.html', {cordinates: obj});  
}); 
    app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});
}

In the html file:

在html文件中:

<%= cordinates.obj %> 

I hope you can help me, solve this problem! :-)

希望你能帮助我,解决这个问题! :-)

Greetings, JS

1 个解决方案

#1


1  

Well, I think here is the problem: you are passing obj to render as coordinates, so you should use coordinates variable in your template directly, no it's obj property, which is non-existent. I'm not sure if it will be rendered as proper array though, maybe you'll need a loop to print it's elements.

好吧,我认为这是问题所在:你将obj传递给渲染为坐标,所以你应该直接使用模板中的坐标变量,不是它的obj属性,这是不存在的。我不确定它是否会被渲染为正确的数组,也许你需要一个循环来打印它的元素。

#1


1  

Well, I think here is the problem: you are passing obj to render as coordinates, so you should use coordinates variable in your template directly, no it's obj property, which is non-existent. I'm not sure if it will be rendered as proper array though, maybe you'll need a loop to print it's elements.

好吧,我认为这是问题所在:你将obj传递给渲染为坐标,所以你应该直接使用模板中的坐标变量,不是它的obj属性,这是不存在的。我不确定它是否会被渲染为正确的数组,也许你需要一个循环来打印它的元素。