I need a random generation of questions in one.js file, later I check the input checkbox by id and output the result at the end. And for the quick displaying questions, I use.handlebars. I need to make a quiz. (modules - express, express-handlebars)
Just in case server.js
const express = require("express"),
app = express(),
exphbs = require("express-handlebars");
const routes = require("./routes/index");
app.listen(3000);
app.use(express.static("public"));
app.engine(
"handlebars",
exphbs({
defaultLayout: "main",
})
);
app.set("view engine", "handlebars");
app.use("/", routes);
I have a data.json file with questions (there are actually more than 1000)
(data = [
{
"ids": "1",
"question": "how?",
"answers": [
"1assd",
"2asdsa",
"3sadas",
"4asdas",
"5asdsad"
],
"correct": [1, 2, 3, 4]
},
{
"ids": "2",
"question": "where?",
"answers": [
"1sadas",
"2sdadsaf",
"3sadsa"
],
"correct": [1, 2, 3]
},
]
I open it in my public/js/app.js and randomize the questions
var mydata = JSON.parse(JSON.stringify(data));
let questi = []; // <------- to index.js ?
for (let i = 0; i <= 2; i++) {
questi[i] = mydata[Math.floor(Math.random() * mydata.length)];
}
console.log(questi);
But don't know how questi send to routes/index.js
const express = require("express"),
fs = require("fs"),
router = express.Router();
router.get("/", function (req, res) {
res.render("test", {
style: "main",
quests: questi, // <------------- from app.js ?
});
});
module.exports = router;
Is it possible to do this somehow differently, so that my views/test.handlebars can easily take values?
{{#each quests}}
<div id={{ids}}>
<ul>
<h3>{{question}}</h3>
{{#each answers }}
<li><input type="checkbox" id={{../ids}}_{{@key}} value="{{@key}}">{{.}}</li>
{{/each}}
<hr>
</ul>
</div>
{{/each}}
<p>answered:</p>
And just in case views/layouts/main.handlebars
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{title}}</title>
<link rel="stylesheet" href="/css/{{style}}.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
{{{body}}}
</body>
<script type="text/javascript" src="data.json"></script>
<script type="text/javascript" src="js/app.js"></script>
</html>
I make a link for.json and with fetch
take values
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.