Controllers
Creating a Controller
To further enhance modularity, it's recommended to utilize controllers, especially for larger applications. Let's create a controller file named src/controllers/PagesController.js
and add the following code to it. Incorporate your view into the controller and pass in template data such as title and description.
Creating the Controller
Create the file src/controllers/PagesController.js
and add the following code:
Note: You can also reuse the same view multiple times within the same method, as explained in more detail in the views section.
Edit the Router
Now that we have created the controller, we need to establish a connection between it and the router. Let's open up the router example again and make the following changes:
Add the import statement for the
PagesController
at the top of the router filesrc/routes/app.js
:
Update the router routes for the start and about pages as follows, connecting your controller to each route:
Summary
And that's it! You have now created a highly modular and dynamic app. Visit your browser to see the results.
Last updated