List Views made Easy
Rendering the Gallery
Section titled “Rendering the Gallery”Now that we have our projects array, we can pass it to our EJS view.
The Middleman: Router
Section titled “The Middleman: Router”Before we can render the view, we need a route to handle the request and fetch the data.
routers/projectRouter.js
const express = require("express");const router = express.Router();const _projectOps = require("../data/projects");
router.get("/", async (req, res) => { const projects = await _projectOps.getProjectList(); res.render("projects-list", { projects });});
module.exports = router;Don’t forget the wires! A router is useless unless server.js knows about
it. In server.js make sure to import and use the router.
const projectRouter =require(”./routers/projectRouter”);
// …
app.use(“/projects”,projectRouter);
EJS Time:
Section titled “EJS Time:”views/projects-list.ejs
<h2>Project Gallery</h2>
<% if (projects.length > 0) { %><ul> <% projects.forEach(project => { %> <li> <a href="/projects/<%= project.slug %>"> <%= project.title %> </a> </li> <% }) %></ul><% } else { %><p>No projects found. Check back later!</p><% } %>Logic Breakdown
Section titled “Logic Breakdown”- Check for Empty: Always check
projects.length > 0to avoid rendering an empty list. - Looping: Use
.forEachto iterate through the documents. - Linking: We use
project.slugin the URL to create a readable link.
⏭ Next: Precision Finding
Section titled “⏭ Next: Precision Finding”We can list them all. Now let’s pick one out of the crowd.