Skip to content
Stefano Azzolini edited this page Dec 12, 2016 · 8 revisions

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

Init view engine


You can select a view engine with the View::using($engine_instance) method.

View::using(new View\PHP(__DIR__.'/templates'));

Create a view


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",
]);

Rendering a view


A view renders itself when casted to a string.

echo View::from('index');

Passing data to a view


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>

Create a view with parameters shorthand


As a shorthand you can pass parameters to the view directly to the from factory method.

echo View::from('index',[
  'title' => 'Index page',
]);
Clone this wiki locally