Home > OS >  Use ENUM in EJS view
Use ENUM in EJS view

Time:07-16

I have a db with a "Requests" table which has a field "status" as INTEGER, I fetch its data in my index and show the different requests.

app.get("/", async (req, res) => {
    try {
        db.open();
        const requests = await db.getRequestsByUserID(req.user.ID);
        db.close();
        res.render("index.ejs", { requests: requests });
    } catch (e) {
        console.log(`Error while showing requests: ${e}`);
        db.close();
        res.render("index.ejs", { name: req.user.first_name, requests: [], error: "Cannot show requests" });
    }
});

I want each request status to be shown (in my EJS view) as a String. For example I have status value 2: i want to print "Accepted".

I've created a status.js like so:

module.exports = {
    1: "Pending",
    2: "Accepted",
    3: "Rejected",
    4: "Cancelled"
}

I figured out you can get the value in the server.js like so:

const STATUS = require("./public/js/status");
console.log(STATUS[2]) // this prints "Accepted"

How do I get the same value when I show each request in my EJS?

CodePudding user response:

well, now you can pass it to the view:

const STATUS = require("./public/js/status");
//...
res.render("index.ejs", { requests, STATUS });

and then dynamically use the key to access the value, for example:

<% requests.forEach(request=>{ %>
    <div>status: <%= STATUS[request.status] %></div>
<% }); %>
  • Related