Class: View

View provides a facility for calling functions or templates and returning their data, for the purpose of separating presentational logic from handlers.

Usage:

<?php

// render a view template
echo View::render ('myapp/hello', array ('name' => 'Joe'));

// set parameters first
View::set ('name', 'Jack');
echo View::render ('myapp/hello');

// set a list of parameters first
View::set (array (
    'name' => 'Jill',
    'age' => 28
));

// render a view function
echo View::render (function ($params) {
    return sprintf ('<p>%s</p>', join (', ', $params));
});

// render a template from within a view function
echo View::render (function ($params) {
    return View::render ('myapp/hello', $params);
});

// pass $page to your view function
echo View::render (function ($params) use ($page) {
    return sprintf ('<p>Layout: %s</p>', $page->layout);
});

?>

Assuming myapp/hello contains <p>Hello {{name}}</p>, then the above will output:

<p>Hello Joe</p>
<p>Hello Jack</p>
<p>Jill, 28</p>
<p>Hello Jill</p>
<p>Layout: default</p>

Note: To pass the controller to a view function, here's how you do it:

<?php

// reassign the controller, since
// we can't pass $this to use()
$c = $this;

echo View::render (function ($params) use ($c) {
    if (! $c->is_https ()) {
        $c->force_https ();
    }
    // continue with rendering...
});

?>

Properties

public static $tpl = Template

The template renderer.

public static $params = array ()

Parameters passed to the next render() that were assigned via set().

Methods

public static init ($tpl)

Sets the template renderer. The renderer can be any object that satisfies the following interface:

interface AbstractTemplateRenderer {
    public function render ($template, $data = array ());
}

public static set ($name, $value)

Set a parameter or list of parameters. Accepts a key/value pair, or a single array or object.

public static render ($view, $params)

Renders a view. Accepts either a function and its parameters, or a template path and the data to pass to it.