无法访问车把中的数组数据

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

我在将数据渲染到车把中时遇到困难。我在视图中尝试了 {{#each}} 和 {{if}} 进程,如下所示:

{{#each obj}}
{{title}}
{{/each}}

(缩写)json 响应如下,我试图访问数组中每个项目的标题、日期和内容:

{
  "content": [
    {
      "title": "Meta Platforms Inc (NASDAQ: META) Stock Analysis: Recovery After Surprise Drop",
      "date": "2024-05-05 04:01:18",
      "content": "<h1>Meta Platforms Inc (NASDAQ: META) Stock Analysis: A Surprising Turn and Recovery</h1>\r\n<p>On April 25th, <a href=\"https://site.financialmodelingprep.com/financial-summary/META\">Meta Platforms Inc (NASDAQ: META)</a> experienced a surprising <strong>14%</strong> drop in stock price at the market open, despite reporting first-quarter earnings that exceeded expectations. The company announced earnings of <strong>$4.71</strong> per share, surpassing the forecasted <strong>$4.32</strong>. Following this initial decline, Meta's stock managed to rebound by more than <strong>8%</strong>. Despite the positive earnings report, the stock's unexpected drop puzzled investors but also indicated a potential hidden opportunity as it began to recover.</p>\r\n<p>The initial shock to Meta's stock price, despite outperforming earnings expectations, reflects the complex dynamics of investor sentiment and market reactions. However, the swift recovery and subsequent stability above the <strong>$400</strong> mark, particularly with the stock finding support at <strong>$414</strong>, underscore a strong investor confidence in Meta's fundamentals and future prospects. This resilience is further evidenced by the stock's performance, with a notable increase of <strong>$10.28</strong>, or approximately <strong>2.33%</strong>, trading at <strong>$451.96</strong>.",
      "tickers": "NASDAQ:META",
      "image": "https://portal.financialmodelingprep.com/positions/66373e5a2712335b9eeccbc4.jpeg",
      "link": "https://financialmodelingprep.com/market-news/meta-platforms-nasdaq-meta-stock-analysis-recovery",
      "author": "Tony Dante",
      "site": "Financial Modeling Prep"
    },

渲染新闻视图的请求如下:

router.get('/news', function(req, res) {
  var url = 'https://financialmodelingprep.com/api/v3/fmp/articles?page=0&size=5&apikey=apikey'

  request(url, function (error, response, results) {
    if (!error && response.statusCode == 200) {
      fs.writeFile('data/news/news.json', results, function (err) {
        //console.log(results)
        var obj = JSON.parse(results);
        console.log(obj)
        console.log("The file was saved as news.json");
      res.render('news', {obj})
        //res.render('news', { obj });
        if (err) {

          return console.log(err);
        }

      });

    }

  });
})

json express handlebars.js
1个回答
0
投票

在 Handlebars 中,循环数组或集合的过程称为“each”块。因此,在提供的代码片段中,{{#eacharticles}}启动一个“each”块,其中articles是正在迭代的数组。在此块中,每次迭代代表文章数组中的一项,并且针对数组中的每一项处理块中的内容。

    {{#each articles}}
        <div>
            <h2>{{title}}</h2>
            <p>Date: {{date}}</p>
            <p>{{{content}}}</p>
            <p>Author: {{author}}</p>
            <p>Site: {{site}}</p>
            <a href="{{link}}">Read More</a>
            <img src="{{image}}" alt="{{title}}">
        </div>
        <hr>
    {{/each}}

此代码使用 Express.js 设置 Web 服务器来呈现新闻页面。它使用 Axios 从金融 API 获取最新的新闻文章。 然后,它使用 Handlebars 模板动态呈现检索到的文章。 最后,它侦听端口 3000 上的传入请求,允许用户通过 Web 浏览器访问新闻页面。

演示代码

 app.js

 views/news.hbs

app.js

import express from 'express';
import exphbs from 'express-handlebars';
import path from 'path';
import axios from 'axios';

const app = express();

const __dirname = path.dirname(new URL(import.meta.url).pathname);

// Configure Handlebars engine
app.engine('.hbs', exphbs.engine({
    extname: '.hbs',
    defaultLayout: false,
    layoutsDir: path.join(__dirname, 'views/layouts')
}));

app.set('view engine', '.hbs');
app.set('views, __dirname + ./views');

// Define route to fetch news articles from API
app.get('/news', async (req, res) => {
    try {
        // Make GET request to the API endpoint
        const response = await axios.get('https://financialmodelingprep.com/api/v3/fmp/articles?page=0&size=5&apikey={your API Key}');
        
        const articles = response.data.content; // Extract relevant data from the response
        
        // Render the 'news.hbs' view and pass the articles data
        res.render('news', { articles });
    } catch (error) {
        console.error('Error fetching data:', error);
        res.status(500).send('An error occurred while fetching data.');
    }
});

const PORT = process.env.PORT || 3000; // Start the server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Note:
替换为
{your API Key}

./views/news.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>News</title>
</head>
<body>
    <h1>Latest News</h1>
    {{#each articles}}
        <div>
            <h2>{{title}}</h2>
            <p>Date: {{date}}</p>
            <p>{{{content}}}</p> <!-- Use triple curly braces to render HTML content -->
            <p>Author: {{author}}</p>
            <p>Site: {{site}}</p>
            <a href="{{link}}">Read More</a>
            <img src="{{image}}" alt="{{title}}">
        </div>
        <hr>
    {{/each}}
</body>
</html>

安装依赖项

npm install express express-handlebars path axios

运行它

node app.js

打开它

通过浏览器

http://localhost:3000/news

结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.