NanoMVC

Views

What is a view?

View files contain the final presentation elements of your content, such as HTML markup and styling. They are responsible for how your application appears to the user.

Learning by example

View files are stored in the /myapp/views/ directory. Here's a basic structure:

/myapp/
  /views/
    hello_view.php

Although not mandatory, it's recommended to append _view to view filenames to distinguish them from other files.

hello_view.php

<html>
  <head><title>Hello</title></head>
  <body>
    Hello World.
  </body>
</html>

To load this view from a controller:

class Hello_Controller extends NanoMVC_Controller {
  function index() {
    $this->view->display('hello_view');
  }
}

Note: always omit the .php extension when specifying the view name.

Loading http://localhost/index.php/hello will display:

<html>
  <head><title>Hello</title></head>
  <body>
    Hello World.
  </body>
</html>

Capture view output to a variable

If you want to capture the view output instead of displaying it directly, use $this->view->fetch():

class Hello_Controller extends NanoMVC_Controller {
  function index() {
    $output = $this->view->fetch('hello_view');
  }
}

Assigning variables to the view

To pass data to your views, use assign(). Here's how:

class Hello_Controller extends NanoMVC_Controller {
  function index() {
    $this->view->assign('title', 'Hello');
    $this->view->assign('body_text', 'Hello World.');
    $this->view->display('hello_view');
  }
}

hello_view.php

<html>
  <head><title><?=$title?></title></head>
  <body>
    <?=$body_text?>
  </body>
</html>

This outputs the same result, but with content injected from the controller:

<html>
  <head><title>Hello</title></head>
  <body>
    Hello World.
  </body>
</html>

You can also assign data using an array:

$data['title'] = 'Hello';
$data['body_text'] = 'Hello world.';
$this->view->assign($data);

All variables assigned with assign() are internally stored in $this->view->view_vars and extracted for use in all views.

If you want variables to apply only to a specific view, pass them as a second parameter to display():

$data['title'] = 'Hello';
$data['body_text'] = 'Hello world.';
$this->view->display('hello_view', $data);

Note: This example uses static text for simplicity. In real applications, content should come from models, config files, or libraries. Avoid embedding content directly in controllers or models to maintain proper MVC architecture.

← to Controllers to Models →

← Back to Documentation