1

I am building a node app with express. The views are in EJS.

I have a list of EJS views. Instead of writing a different route for each of these views, is there a way to have only one dynamic route "/:dynamic_route" and then and then render the corresponding view dynamically too?

Just to be clear, I don't have/need any dynamic content in these EJS views. I only want to be able to loop through them and render the one that matches the URL I want to access. So, in the code below, how could I do it within the res.render parenthesis?

exports.viewTemplate(req, res) {
//some code to match the requested url and the corresponding view
res.render("dynamically_reference_view")
}
thealchemist
  • 421
  • 4
  • 12
piraha
  • 65
  • 10

1 Answers1

0

I have managed to come up with a satisfactory solution.

In the router

router.get("/:dynamic_route", controller.viewTemplate)

In the controller

exports.viewTemplate = function(req, res) {
let view = req.url.slice(10) //Remove beginning of the path until only the filename of the template to be rendered is left

res.render(view)

}

piraha
  • 65
  • 10