我有个问题。如何呈现从get请求中获得的api数据,并使用handlebars将其显示在我的网站上?数据包含一个图像和一个描述。
下面是我在index.js中的代码:
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代码:
<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数据,我有这些值,但无法显示:
[
{
"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
}
]
发布于 2020-11-26 06:14:46
这是通过搜索"javascript express handlebar“获得的an article I found。
这使用了一个包npm install express-handlebars
。
就像@danibrum提到的那样,您将handlebars定义为engine
。这篇文章很好地概述了它是如何工作的。
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}`))
https://stackoverflow.com/questions/65013262
复制相似问题