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/templates/Pages.js and add the following code to it. Incorporate your view into the controller and pass in template data such as headline and content.

import { text } from "@/templates/views/text";

export class Pages {
    
    start(request, container, helper, builder) {

        this.view(text, {
            headline: "Hello world!",
            content: "Lorem ipsum dolor",
        });

        return this;
    }
    
    about(request, container, helper, builder) {

        this.view(text, {
            headline: "About us",
            content: "Lorem ipsum dolor",
        });

        return this;
    }
}

Note: You can 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:

First, add the import statement for the Pages controller at the top of the router file src/routes/app.js:

import { Pages } from '@/controllers/Pages';

Then, update the router routes for the start and about pages as follows, connecting your controller to each route:

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

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 Views

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