Template

Templates

$content = $this->template('products/list', compact('products'));
  • This assumes the controller extends BaseController, which has a method template().
  • That method likely renders a PHP template, like templates/products/list.php, and returns the rendered HTML as a string.
  • compact('products') creates an associative array like ['products' => $products] for use in the template.

In the template, you’d access products like:

foreach ($products as $product) {
    echo $product['name'] ;
}

BaseController

The controller extends BaseController, which is not shown. The template() method is used to load and display a PHP view file (template) and make some data (like session and auth helper) available to it.

If you call:

$this->template('products/list', ['products' => $products]);

Then inside templates/products/list.php, you can use:

$products (from parameters)

$session (from the request)

$authHelper (from controller)

layout for simple crud

Now let's build simple layout for our example which we can use for listing the products as well creating/editing any product with form. Let's create a layout file inside templates directory called templates/product_layout.php

<!DOCTYPE html>
<html>
<head>
    <title>Layout with Sections</title>
    <link rel="stylesheet" href="<?= assetPath('styles/app.css') ?>">
    <?= App\Utils\View::getSection('head') ?>
</head>
<body>
    <header><h1>Product Portal</h1></header>
    <a href="<?= route('')?>">Product List</a>
    <a href="<?= route('')?>">Create New Product</a>
    <main><?= $content ?></main>
    <footer><small>Footer</small></footer>
    <script src="<?= assetPath('js/app.js') ?>"></script>
    <?= App\Utils\View::getSection('scripts') ?>
</body>
</html>

Now we do not have to write menu and app.css and app.js includes in every php view files that is needed for CRUD functionality. We have defined this stufs in above layout. Now we will use this layout in other words we will extends this layout in our view(template) php files. Let see an exampe of products/list.php