Screencast #04 - View rendering and module config

View rendering and module config

In the past few articles, we have looked at the basics of modules and routing. However, our first controller only returned simple strings. This week, let us look at actual view rendering.

Render a view from a controller action

To pass parameters to the view renderer, a controller action returns a PHP array. The reserved key $view holds parameters for the view renderer, i.e. the name of the view file to render.

public function indexAction()
{
    return [ 
'$view' => [ 'title' => 'TODO management', 'name' => 'todo:views/admin/index.php' ], 'message' => 'Hello how's it going?' ]; }

The rendered view file can be a plain PHP template. Simple parameters (i.e. message) are available as PHP variables (i.e. $message).

packages/pagekit/todo/views/admin/index.php:

<h1><?php echo $message; ?></h1>

Resource shorthands

Instead of referencing the full path to a file, we can use a shorthand syntax. packages/pagekit/todo/views/admin/index.php turns into todo:views/admin/index.php. This is faster to type and nicer to read.

You can register shorthands with a target path in your index.php. In this example we want to point todo: to the curent path of the index.php.

'resources' => [
    'todo:' => ''
],

Module config

A module can come with a configuration array to hold any kind of settings. We can use this as a simple storage for our TODO items.

'config' => [
    'entries' => [
        ['message' => 'Buy milk.', 'done' => false], // ...
    ]
],

From the controller, we can access this configuration as a property of the module instance.

src/Controller/TodoController.php:

use Pagekit\Application

// ...

$module = App::module('todo');
$config = $module->config;

// ...

We can store changes to the module config in the database. The changes from the default module config are merged with the stored changes so that we always have a valid configuration available in the controller.

// modifying the module config
App::config('todo')->set('entries', $entries);

Feedback and Comments

With the steps explained in the past few videos and articles, we hope to give you a good idea of how to create your own extension. In the next step, we'll round it up with a small introduction to Vue.js.

Have a look at the Pagekit Documentation to read more about Extension Development and View rendering.

For feedback on this article and ideas for upcoming videos, please leave your comment below or say hi in our developer chat.

Here is a short list of all existing screencasts:

Florian
Posted by Florian
{{ message }}

{{ 'Comments are closed.' | trans }}