Layouts and Views
Layouts are tipically the main HTML structure of pages which holds different views. A view is a small part of a layout. Layouts include views. Let say you have two pages "FAQ" and "Contact". Their structure with <header>, <footer> and <sidebar> is the same. There is no need to duplicate the content of these pages. Instead, you can create a layout which holds these elements, and for the content of the <main> you can define two views, which are included in the layout. An example:
<?php
declare(strict_types=1);
namespace workspace\site\controllers;
use nicotine\Controller;
class Articles extends Controller {
public function __construct()
{
// Required, if you use class constructor.
parent::__construct();
// Setting the layout in the controller means that all the methods (aka actions) will use the same layout.
// The location of the file is /workspace/site/layouts/my-articles.php
$this->proxy->layout = 'my-articles';
}
/** List articles */
public function list()
{
// Or you can set the layout per method.
$this->proxy->layout = 'theme-2-articles';
$articles = []; // Get them from database...
$this->proxy->view(
// This points to the file /workspace/site/views/articles/list.php
// As a good practice, you can set the name of the folder /articles/ to be the same as the controller name, but in lowercase.
'articles/list',
// The variable will be available into the view as "$this->vars->articles"
compact('articles')
);
}
}
Create the file (the layout) /workspace/site/layouts/my-articles.php:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<?php print $this->contentForLayout; ?>
</body>
</html>
The view (aka content for layout):
<?php foreach ($this->vars->articles as $article) { ?>
<p><?php print $article['title']; ?></p>
<?php } ?>