-
Notifications
You must be signed in to change notification settings - Fork 4
Views
It wouldn’t be very good practice to mix up all of our logic and presentation, and that’s why Tessera supports views and layouts. They’re also both completely optional, how is Tessera supposed to know what kind of application you’ve made? Maybe all it does is echo JSON, you probably wouldn’t need any views or layouts for that.
A view is included if it exists. Both views and layouts are stored in the views directory relative to the application’s PHP file, and the name of the view is method_name.html. For example, the route ‘/foo/bar’ => ‘foo’ would have the view views/foo.html. That’s not forced though, you can change the name of the view you use. In the method, call $this->view = 'viewname'
to use views/viewname.html. If you don’t want to use a view, but the file exists, just call $this->view = null
to turn it off.
Like views, layouts are also completely optional. You can use layouts to give your application a uniform look, as well as DRY up your markup. To use a layout, set the variable $this->layout
to the name of the layout you want to use. If that variable isn’t set, no layout will be used. It’s also possible to change the layout inside of a method.
To display the output of a view inside of a layout, use the $this->view_output
variable. Here’s a simple layout example:
<h1>Layout</h1>
<div>
<?php echo $this->view_output; ?>
</div>
In case you were wondering, yes, the $this->script_output
variable is also available. It’s the captured output from the method.
You can pass data from methods to views and layouts by using the Tessera::set
method. Here’s a simple example method and associated view:
function foo() {
$pokemon = array('Bulbasaur', 'Squirtle', 'Charmander');
$this->set('starters', $pokemon);
}
The call to $this->set('starters', $pokemon)
makes the $pokemon
variable available to views and layouts as $starters
. The view looks like this:
<ul>
<?php foreach($starters as $starter): ?>
<li><?php echo $starter; ?></li>
<?php endforeach; ?>
</ul>
It makes for clean separation of logic and presentation, as well as clean code from using PHP’s alternative syntax.