Pug 无法读取数组,但仅限于迭代它时

问题描述 投票:0回答:1

我正在为我的大学课程开发一个小型 Web 开发项目,以 pug 作为视图引擎进行表达。我希望迭代一系列气象站,为每个气象站创建一条路线,并在详细信息页面中显示该数组的值。

var i = 0;
while(stations[i]!= null){
    app.get('/'+stations[i]["name"], (req, res) => {
        res.render("DetailsTemplate", {Station: stations[i]})
    });
    console.log(`detailsPageRunning on ` + '/' + stations[i]["name"] + ' '+ i);
    i++;
}
block content
    div(class="details")

        div(class="station")
            div(class="station-element")
                h2 #{Station.name}
                p
            div(class="station-element")
                h2 Wetter
                p #{Station.readings.at(0).wetter}
            div(class="station-element")
                h2 Temperatur
                p #{Station.readings.at(0).temp} Grad
            div(class="station-element")
                h2 Wind
                p #{Station.readings.at(0).wind} bft.
            div(class="station-element")
                h2 Luftdruck
                p #{Station.readings.at(0).luftdruck} bpa

现在,路由已按照我想要的方式创建,并且如果我在每次迭代中都提供相同的数组,则页面能够正常渲染。例如

Station: stations[0]
效果很好。如果我不能在每条路线上都有不同的值,那么它就有点无用了。为什么
Station: stations[i]
不起作用?我需要改变什么才能让它工作?

我尝试过使用其他阵列,以查看天气问题是否出在该阵列上,但这些都显示出相同的问题。

javascript express pug
1个回答
0
投票

您的代码已经奠定了基础,下面的代码澄清了其中的某些要点。请看看是否有用。该代码使用了一系列路由路径。还有另一种使用路由参数的方法,单独发布。

const express = require('express');

const app = express();

// sample data
const stations = [
  { name: 's-one', readings: [{ wetter: 10, temp: 4, wind: 1, luftdruck: 5 }] },
  {
    name: 's-two',
    readings: [{ wetter: 12, temp: 14, wind: 13, luftdruck: 3 }],
  },
];

// array of route paths e.g. [/s-one, /s-two]
const routepaths = stations.map((i) => '/' + i.name);

// route paths in array
app.get(routepaths, (req, res, next) => {
  // finding station with respect to the given request
  const station = stations[routepaths.findIndex((i) => i == req.url)];

  if (station) {
    // call render here as this
    //res.render('DetailsTemplate', { Station: station });

    // this send is just for testing this sample code
    res.send(station);
  }
});

// This a catch-all middleware
// it is required in case an invalid request is made
app.use((req, res, next) => {
  res.status(404).send('Route not found');
});

// this is the custom error handler
app.use((err, req, res, next) => {
  res.status(500).send(`Some error : ${err.message}`);
});

app.listen(3000, () => console.log('L@3000'));

测试有效请求:

   Request:  curl http://localhost:3000/s-one
   Response: {"name":"s-one","readings":[{"wetter":10,"temp":4,"wind":1,"luftdruck":5}]}

测试无效请求:

   Request: curl http://localhost:3000/s-onex
   Response: Route not found
© www.soinside.com 2019 - 2024. All rights reserved.