Views
A view is a full page or a page fragment—like a header, footer, or sidebar—and can be freely nested to form hierarchical layouts.
Creating Views
To understand, you can follow the example below, creating 3 files:
system/views/blog/header.php:
<header>
<h1>My Blog</h1>
</header>
system/views/blog/header.php:
<footer>
<p>© <?=gmdate('Y')?> Meu Blog</p>
</footer>
system/views/blog/index.php:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Blog</title>
<link rel="stylesheet" type="text/css" href="blog.css" />
</head>
<body>
<?php
View::render('blog.header');
?>
<main>
<h2><?=$title?></h2>
<p><?=$contentes?></p>
</main>
<?php
View::render('blog.footer');
?>
</body>
</html>
Then in the controller, callable, or closure, call the View::render() method like this:
$app->action('GET', '/blog', function ($app, $params) {
$entries = [
'title' => 'My Blog',
'contentes' => 'Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.',
];
View::render('blog.index', $entries);
});
It's important to note that the view is only rendered after the route has been processed or if a serious exception or error occurs. Therefore, within a closure, callable, or controller method, you can use functions to control the header without worrying about errors, and you can define them in any order, for example:
$app->action('GET', '/foo', function ($app, $params) {
View::render('bar.baz');
header('Pragma: public');
setcookie('mycookie', time());
});
Share variables between views
With the View::share method you can share a value that will be accessible by the same variable in different Views, for example:
$app->action('GET', '/blog', function ($app, $params) {
View::data('year', gmdate('Y'));
View::data('hello', 'Hi!');
View::render('foo');
View::render('bar');
});
system/views/foo.php:
<section>
<h2>Foo view</h2>
<p><?=$year?> - <?=$hello?></p>
</section>
system/views/bar.php:
<section>
<h2>Bar view</h2>
<p><?=$year?> - <?=$hello?></p>
</section>
<?php
View::render('baz');
?>
system/views/baz.php:
<section>
<h2>Baz view</h2>
<p><?=$year?> - <?=$hello?></p>
</section>