-
Notifications
You must be signed in to change notification settings - Fork 10
View
The View module handles the rendering of templates via various engines.
Core ships a vanilla PHP template engine (View\PHP
), you can find other bridges in the caffeina-core repository
You can select a view engine with the View::using($engine_instance)
method.
View::using(new View\PHP(__DIR__.'/templates'));
You can create a view object the View::from($template_name)
factory method.
The $template_name
is the relative path of the template inside the template directory.
Extension must be omitted, it's automatically handled by the engine.
// Prepares /templates/index.php
$index_page = View::from('index');
// Prepares /templates/errors/404.error.php
$error_page = View::from('errors/404.error');
If you need a chain of fallbacks for templates (just like wordpress template hierarchy) pass an array of template names, they will be resolved in a top-bottom sequence.
// Search for /templates/article-{id}.php
// or /templates/article-{slug}.php
// or fallback to /templates/article.php
$article = new Article;
$index_page = View::from([
"article-{$article->id}",
"article-{$article->slug}",
"article",
]);
A view renders itself when casted to a string.
echo View::from('index');
You can pass data to a view via the with(array $variables)
method.
echo View::from('index')->with([
'title' => 'Index page',
'toc' => [
'First',
'Second',
'Third',
],
]);
You can use the passed variables directly in the template (example uses the twig engine )
<h1>{{ title }}</h1>
<ul>
{% for item in toc %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Renders
<h1>Index page</h1>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
As a shorthand you can pass parameters to the view directly to the from
factory method.
echo View::from('index',[
'title' => 'Index page',
]);
Core is maintained by using the Semantic Versioning Specification (SemVer).
Copyright 2014-2016 Caffeina srl under the MIT license.
http://caffeina.com