In this example, the layout file:
<?php
/**
* views/layouts/main-layout.php
*
* @var $this \Nullai\Vista\Engines\ViewRenderEngine
*/
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Site</title>
<?php $this->yield('scripts'); ?>
</head>
<body>
<?php $this->yield('main'); ?>
<?php $this->include('sidebar', ['menu' => ['Home', 'About', 'Contact']]); ?>
<?php $this->yield('footer'); ?>
</body>
</html>
The include('sidebar', ['menu' => ['Home', 'About', 'Contact']])
method passes a menu variable to the sidebar.php
view.
Inside sidebar.php
, the $menu
array will be accessible.
<?php
/**
* Sidebar view file
* @var array $menu The array of menu items passed to this view
* @var $this \Nullai\Vista\Engines\ViewRenderEngine
*/
?>
<aside class="sidebar">
<nav class="menu">
<ul>
<?php foreach ($menu ?? [] as $item): ?>
<li>
<a href="#"><?= htmlspecialchars($item, ENT_QUOTES, 'UTF-8') ?></a>
</li>
<?php endforeach; ?>
</ul>
</nav>
</aside>
Advanced Include Features
Expanding the project to include a users’ folder.
project-root/
├── vendor/
│ └── autoload.php
├── views/
│ ├── layouts/
│ │ └── main-layout.php
│ ├── users/ # Users folder
│ │ ├── parts/ # Partials folder
│ │ │ └── form.php # User edit form
│ │ └── index.php # User index
│ │ └── edit.php # User edit
│ └── home.php
│ └── sidebar.php
├── public
│ └── index.php
Relative Include
To include a view relative to the current view file prefix the include value with :
:
<?php
/**
* views/users/edit.php
*
* @var $this \Nullai\Vista\Engines\ViewRenderEngine
* @var $content string
*/
$this->layout('layouts.main-layout');
echo $content;
?>
<?php $this->include(':parts/form', ['form' => $form]); ?>
Conditional Include
You can also include with includeIf()
which will only include the view if conditionals are meet:
<?php
/**
* views/users/edit.php
*
* @var $this \Nullai\Vista\Engines\ViewRenderEngine
* @var $content string
*/
$this->layout('layouts.main-layout');
echo $content;
?>
<?php $this->includeIf(!empty($form), ':parts/form', ['form' => $form]); ?>
File Include
You can include a specific file using its absolute path:
<?php
/**
* views/users/edit.php
*
* @var $this \Nullai\Vista\Engines\ViewRenderEngine
* @var $content string
*/
$this->layout('layouts.main-layout');
echo $content;
?>
<?php $this->include(__DIR__ . '/parts/form.php', ['form' => $form]); ?>