Gallery3:Developer Handbook:Views - Gallery Codex
Personal tools

Gallery3:Developer Handbook:Views

From Gallery Codex

Views

A view is a PHP file that lives in the views directory of your module, typically used to display HTML content to the web browser.. Controllers and helpers can access views by using Kohana’s View PHP class. Views are typically predominantly HTML with some PHP sprinkled in to show data from models and other sources.

To display the title and owner of an item, the controller and view combination might look like this:

modules/example/controllers/title_and_owner.php:

 <?
 class Title_And_Owner_Controller extends Controller {
   public function show($id) {
     $item = ORM::factory("item", $id);      // Load the item model
     access::required("view", $item);        // Check permissions
     $v = new View("title_and_owner.html");  // Load up our view
     $v->item = $item;                       // Set a view variable
     print $v;                               // Print results
   }
 }

modules/example/views/title_and_owner.html.php:

<p>
  Hello <b><?= identity::active_user()->name ?></b>!
</p>
<p>
  You’re looking at <?= $item->title ?> which was
  uploaded by <?= $item->owner->name ?>
</p>

While the view has the power to make PHP calls directly, it's a good idea to keep them as simple as possible. When using conditionals or looping in a view, it's common to use PHP's Alternative Control Syntax which is easier to read in templates. For example, to use both looping and conditionals in a template, you might have this:

<? if (!empty($items)): ?>
<ul>
  <? foreach ($items as $item): ?>
    <li>
      <a href="<?= $item->url() ?>">
        <?= $item->title ?>
      </a>
    </li>
  <? endforeach ?>
</ul>
<? endif ?>

The alternate syntax meshes reasonably well with HTML markup. Curly brace style syntax is much harder to read inside templates. If you find yourself writing large chunks of PHP with curly braces in your view, consider moving that code to a controller or a helper.