首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用handlebars将api中的数据呈现为html?

如何使用handlebars将api中的数据呈现为html?
EN

Stack Overflow用户
提问于 2020-11-26 05:57:33
回答 1查看 42关注 0票数 0

我有个问题。如何呈现从get请求中获得的api数据,并使用handlebars将其显示在我的网站上?数据包含一个图像和一个描述。

下面是我在index.js中的代码:

代码语言:javascript
运行
复制
var express = require('express');
var router = express.Router();
const request = require('request');

/* GET home page. */
const menClothing = router.get('/', function(req, res, next) {
     request('URL', { json: true }, (err, res, body) => {
        if (err) { return console.log(err); }
        console.log(body)
    });
    res.render('shop/index', { title: 'Website', categories: menClothing });
});

下面是我的index.hbs代码:

代码语言:javascript
运行
复制
<div class="container">
    <div class="row py-5">
        <div class="col-lg p-3">
            <h4>Clothing</h4>
            <p></p>
        </div>
    </div>
    <h3>Subcategories</h3><hr>
    {{# each categories }}
        <div class="card mb-3">
            <img src="//Here it should be the image" class="card-img-top">
            <div class="card-body">
                <p class="card-text">//Here it should be the description</p>
                <button type="button" class="btn btn-outline-dark">View More</button>
            </div>
        </div>
    {{/each}}
</div>

这是我从api获得的JSON数据,我有这些值,但无法显示:

代码语言:javascript
运行
复制
[
  {
    "image": "photo",
    "_id": "",
    "id": "",
    "name": "",
    "page_description": "",
    "page_title": "",
    "parent_category_id": "",
    "c_showInMenu": true,
    "__v": 0
  },
{
    "image": "",
    "_id": "",
    "id": "",
    "name": "",
    "page_description": "",
    "page_title": "",
    "parent_category_id": "",
    "c_showInMenu": true,
    "__v": 0
  }
]
EN

回答 1

Stack Overflow用户

发布于 2020-11-26 06:14:46

这是通过搜索"javascript express handlebar“获得的an article I found

这使用了一个包npm install express-handlebars

就像@danibrum提到的那样,您将handlebars定义为engine。这篇文章很好地概述了它是如何工作的。

代码语言:javascript
运行
复制
const express = require('express');
const app = express();
const port = 3000;
//Loads the handlebars module
const handlebars = require('express-handlebars');
//Sets our app to use the handlebars engine
app.set('view engine', 'handlebars');
//Sets handlebars configurations (we will go through them later on)
app.engine('handlebars', handlebars({
layoutsDir: __dirname + '/views/layouts',
}));
app.use(express.static('public'))
app.get('/', (req, res) => {
//Serves the body of the page aka "main.handlebars" to the container 
//aka "index.handlebars"
res.render('main', {layout : 'index'});
});

app.listen(port, () => console.log(`App listening to port ${port}`))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65013262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档