【发布时间】:2020-10-08 02:17:12
【问题描述】:
我正在创建一个网站,显示我的项目与他们的 github 存储库链接。
由于抄袭问题,我省略了 Pug 文件。 (这是一个学校项目)
现在,我必须使用动态路由。基于 id(来自 JSON),我需要渲染所需版本的 Pug 项目模板,以显示 JSON 文件中数组列表项目中的单个项目。然后可以通过将它们作为本地人添加到 JS 文件中来将该数据传递给 pug 模板。
我的问题是如何链接 JSON 文件?还是链接数组对象?
我认真地尝试了几个小时来解决这个问题,但没有结果。
如果这是一个非常明显的问题,我很抱歉。
project.pug
h1 Title #{project_name}
p
| #{description}
h6 Technologies
ul
each project in projects
li= project.technologies
app.js
const express = require('express');
const json = require('./data.json');
const path = require('path');
const { query } = require('express');
const app = express();
const read = json();
//Not sure about this ????
const filepath = path.basename('Users/x/Downloads/sem 2/CSIS 3380 Web Programming JS/Session 4/Express Site/public');
app.set('view engine', 'pug');
app.use(express.static('public'));
// render "Home" page with locals set to data.projects
app.get('/index', (req, res) => {
res.render('Home', {
locals: {
'projects': projects
}
});
});
app.get('/about', (req, res) => {
res.render = ('About');
});
//Dynamic routes based on id of project adding locals to pass to pug
app.get('/projects/:id', function(req, res) {
res.render('project', { projects: query.data });
});
app.listen(3000, () => {
console.log("Server started on port 3000");
});
data.json
{
"projects": [{
"id": 0,
"project_name": "Battleships",
"description": "A game that allows you to guess battleships on a gamebaords and reports hits/misses.",
"technologies": ["HTML", "JavaScript", "CSS"],
"image_url": ["", "", ""]
},
{
"id": 1,
"project_name": "Random Quotes Flashcards",
"description": "Flashcards of random famous qoutes from renowned personalities.",
"technologies": ["HTML", "JavaScript", "CSS"],
"image_url": ["", "", ""]
},
{
"id": 2,
"project_name": "BMI",
"description": "A BMI calculator, computes BMI with weight and height inputs.",
"technologies": ["HTML", "JavaScript", "CSS", "Node.js", "pug"],
"image_url": ["", "", ""]
}
]
}
【问题讨论】:
标签: javascript json express routes pug