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:

import Start from "@/templates/views/Start";

export default class PagesController {
    
    start(http, container, helper, context) {
        this.layout(Start, {
            title: "Hello world!",
            description: "Lorem ipsum dolor",
        });

        return this;
    }
    
    about(http, container, helper, context) {
        return `
        <article class="relative card-1 border-bottom ingress">
            <div class="wrapper md">
                <h1 class="headline-1">About us</h1>
                <p>Lorem ipsum dolor</p>
            </div>
        </article>`;
    }
}

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:

  1. Add the import statement for the PagesController at the top of the router file src/routes/app.js:

import PagesController from '@/controllers/PagesController';
  1. Update the router routes for the start and about pages as follows, connecting your controller to each route:

router.get('/', [PagesController, "start"]);
router.get('/about', [PagesController, "about"]);

Summary

And that's it! You have now created a highly modular and dynamic app. Visit your browser to see the results.

Response Arguments

If you want to know more about the response arguments, then visit the Response Arguments page.

Template Layouts

Here are some important options to consider when loading and initializing views:

  • Static Views: These are views that are bundled and loaded synchronously with the application. They are commonly used for static content that does not change frequently. Read more

  • Asynchronous Views: Asynchronous views are loaded dynamically when needed, which can help improve performance by reducing initial load times. They are useful for content that may change frequently or is not required immediately upon application startup. Read more

Last updated