我正在学习如何使用express.js框架,到目前为止还不错。然而,我遇到了一个问题。我有一个json文件与对象和对象元素。对象元素包括**categoryName**
和**linkURL**
。我试图写一个函数,解析这两个元素作为一个链接视图。以下是我尝试过的:这是json文件
{
"categoryName": "Appetizers & Sides",
"categories": [
{
"categoryID": "294",
"parentID": "304",
"subjectID": "7",
"categoryName": "Apps and Side Dishes (Laura)",
"categoryDescription": "Learn to make amazing appetizers and side dishes with Laura in the Kitchen.",
"videosCount": "101",
"forumCategoryID": "163",
"linkURL": "https://thenewboston.com/guide/introduction"
},
{
"categoryID": "285",
"parentID": "304",
"subjectID": "7",
"categoryName": "Side Dishes",
"categoryDescription": "Side dish recipes for salads, vegetables, sauces with Hilah cooking.",
"videosCount": "38",
"forumCategoryID": "163",
"linkURL": "https://thenewboston.com/guide/introduction"
},
{
"categoryID": "337",
"parentID": "304",
"subjectID": "7",
"categoryName": "Side Dishes (bt)",
"categoryDescription": "Side dish recipes with Byron Talbott.",
"videosCount": "5",
"forumCategoryID": "163",
"linkURL": "https://thenewboston.com/guide/introduction"
},
{
"categoryID": "301",
"parentID": "304",
"subjectID": "7",
"categoryName": "Side Dishes for Barbecue",
"categoryDescription": "Barbecue side dish recipes done on the grill by the BBQ Pit Boys!",
"videosCount": "43",
"forumCategoryID": "163",
"linkURL": "https://thenewboston.com/guide/introduction"
},
{
"categoryID": "297",
"parentID": "304",
"subjectID": "7",
"categoryName": "Soups and Salads (Laura)",
"categoryDescription": "Looking for the perfect recipe to start your meal? Or are you looking to eat something on the lighter side? These are sure to have you covered!",
"videosCount": "70",
"forumCategoryID": "163",
"linkURL": "https://thenewboston.com/guide/introduction"
}
]
}
这是我的路由器文件
var express = require('express');
var router = express.Router();
var vd = require('../videodata.json')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' , videodata: vd});
});
module.exports = router;
这就是我在ejs中尝试做的文件
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<% include templates/header.ejs%>
<h1><%= videodata.categoryName %></h1>
<ul>
<% videodata.categories.forEach(function(item){ %>
<li><%=
// TO DO: CREATE LINK TO APPEAR ON WEBSITE
const a = document.createElement('a');
a.href = item.categoryName;
a.innerText = item.linkURL;
document.body.appendChild(a);
%></li>
<% }); %>
</ul>
</body>
</html>
所以我的问题是我如何改变ejs显示链接列表,例如:
- categoryName
- categoryName 链接
linkURL
?您可以使用下面的代码来显示链接列表
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<% include templates/header.ejs%>
<h1><%= videodata.categoryName %></h1>
<ul>
<% videodata.categories.forEach(function(item){ %>
<li> <a href="<%= item.linkURL %>"><%= item.categoryName %></a> </li>
<% }); %>
</ul>
</body>
</html>