Views


1Presentation

The view is the software layer that takes care of formatting the data that is returned by the server after processing.

By default, Temma uses the Smarty template engine, which makes it very easy to generate HTML pages from the data exported by the controllers.

Temma also natively provides a view used to generate JSON feeds, which can be very practical in the context of AJAX communications, as well as views offering CSV, RSS, INI and iCal exports.


2Using a templated view

Some views use templates to process data and generate outgoing flows. As seen in the introduction, Temma will look for a file whose name corresponds to that of the requested action (with the ".tpl" extension), placed in a directory whose name is that of the controller being executed; all placed in the templates/ directory of the project.

To work around this automatic behavior, an action can specify the template to use:

class User extends \Temma\Web\Controller {
    public function list($type=null) {
        // processings...

        // redefining the template in a particular case
        if ($type == 'all')
            $this->_template('user/listAll.tpl');
        // in the other cases, the template will be "user/list.tpl"
    }
}

3View definition

It is possible to specify the view to use, individually for each action.

Here is an example of an action whose data is exported in JSON format:

class User extends \Temma\Web\Controller {
    public function get($id) {
        // processings...

        // set the data that will be sent
        // in the JSON stream
        $this['json'] = $data;

        // definition of the used view
        $this->_view('\Temma\Views\Json');
    }
}

When the view used is a standard view (supplied by Temma), it is possible to shorten its writing by using the tilde character (~) to replace the \Temma\Views\ prefix:

class User extends \Temma\Web\Controller {
    public function get($id) {
        // processings...
        $this->_view('~Json');
    }
}

Temma also offers the \Temma\Attributes\View attribute, which makes it easy to define the view to be used for all controller actions and/or for specific actions:

use \Temma\Attributes\View as TµView;

// controller that uses the JSON view by default
#[TµView('~Json')]
class User extends \Temma\Web\Controller {
    // action that uses the JSON view defined at the controller level
    public function get($id) {
        // processings...
    }

    // action that specifically uses the RSS view
    #[TµView('~Rss')]
    public function stream() {
        // processings...
    }
}

The _view() method also accepts two special values: false disables the processing of the view (the action then writes the output itself), and null (or no parameter) returns to the default view of the configuration, which makes it possible to cancel a view defined by an attribute on the controller. See the documentation of the View attribute for examples.


4Transmitting data to the view

To transmit data to the view, there are two base behaviors:

  • For template-based views (Smarty and PHP), all previously defined template variables (with $this['variable'] = $value;) are passed to the template, as long as the variable name does not start with a single underscore (variables whose name starts with two underscores are passed, like flash variables).
  • Other views expect one or more view-specific template variables (json, csv, data, ical).

Examples:

class User extends \Temma\Web\Controller {
    // using the default Smarty view
    public function get(int $id) {
        // processings...

        // using separate template variables
        $this['user'] = $user;
        $this['activity'] = $activity;
    }

    // using the JSON view
    #[TµView('~Json')]
    public function getActivity(int $id) {
        // processings...

        // using the "json" template variable
        $this['json'] = $activity;
    }
}

It is also possible to define the data to transmit to the view by assigning it to the @output template variable. If this variable is defined, the view uses it in priority instead of the view-specific variable.
For template-based views (Smarty and PHP), if @output is defined, it must contain an associative array whose key-value pairs will be used as template variables (keys starting with a single underscore are removed). If @output is not an array, or if it contains integer keys (list), a \Temma\Exceptions\Framework exception is raised (code BAD_OUTPUT). If @output is not defined, the usual behavior is preserved.
For the JSON and INI views, if neither @output nor the view-specific variable is defined, all template variables are used, except URL, CONTROLLER, ACTION, filename, jsonDebug (JSON view) and the variables whose name starts with an underscore. For the iCal view, the name, description and events template variables are used.

Examples:

class User extends \Temma\Web\Controller {
    // using the default Smarty view
    public function get($id) {
        // processings...

        // defining template variables via @output
        $this['@output'] = [
            'user'     => $user,
            'activity' => $activity,
        ];
    }

    // using the JSON view
    #[TµView('~Json')]
    public function getActivity(int $id) {
        // processings...

        // data is transmitted to the view via @output
        $this['@output'] = $activity;
    }
}

5Configuration of the default view

You have the possibility to change the default view, by modifying the etc/temma.php configuration file.

For example, if you create a webservice, you will never send HTML, but always JSON. You will then want to use the \Temma\Views\Json view instead of the usual Smarty view, you have to add the defaultView directive in the etc/temma.php file:

<?php

return [
    'application' => [
        // usual configuration (dsn, defaultController, ...)

        // configuration of the default view
        'defaultView' => '\Temma\Views\Json'
    ]
];

As seen above, it is possible to replace the \Temma\Views\ prefix with the tilde character (~):

<?php

return [
    'application' => [
        // configuration of the default view
        'defaultView' => '~Json'
    ]
];

6Content type of the response

Each view sends an HTTP Content-Type header matching the format it generates. This default type is defined by the CONTENT_TYPE constant of the view:

View CONTENT_TYPE constant Sent header
Smarty, PHP text/html Content-Type: text/html; charset=UTF-8
JSON application/json Content-Type: application/json
CSV text/csv Content-Type: text/csv; charset=UTF-8
iCal text/calendar Content-Type: text/calendar; charset=UTF-8
INI text/ini Content-Type: text/ini; charset=UTF-8
RSS application/rss+xml; charset=UTF-8 Content-Type: application/rss+xml; charset=UTF-8

This default type can be replaced, for a controller or an action, with the _contentType() method of controllers or with the ContentType attribute. The type can be a full MIME type or an alias (json, csv, html…). This is useful, for example, to serve a robots.txt file or a Markdown document generated by a Smarty template:

use \Temma\Attributes\ContentType as TµContentType;

class Site extends \Temma\Web\Controller {
    // the "site/robots.tpl" template is sent as "text/plain; charset=UTF-8"
    #[TµContentType('text/plain')]
    public function robots() {
        // ...
    }

    // content type defined in the action's code
    public function readme() {
        $this->_contentType('text/markdown');
        // ...
    }
}

Character set: if the content type is of the form text/* (or is application/rss+xml or application/xhtml+xml) and does not contain a charset indication, the view appends ; charset=UTF-8 to it. Thus text/plain becomes text/plain; charset=UTF-8, whereas text/plain; charset=ISO-8859-1 and image/png are sent as is.

Header order: the view first sends the Content-Type header, then the generic cache-disabling headers (Cache-Control, Expires, Pragma), then the default headers of the configuration, and finally the specific headers defined with the _header() method (as well as the Content-Disposition header of downloadable views). The public buildHeaders() method of the view builds this list, and sendHeaders() sends it.

Custom views: to define the content type of an application view (a class extending \Temma\Web\View), simply override the CONTENT_TYPE constant. The type defined by the controller, if any, takes precedence over this constant:

use \Temma\Attributes\View as TµView;

// view that sends the binary data of the "data" variable as is
class Binary extends \Temma\Web\View {
    const CONTENT_TYPE = 'application/octet-stream';

    public function sendBody() : void {
        print($this->_response->getData('data'));
    }
}

// controller that uses this view, adapting the type to the served file
#[TµView('\Binary')]
class Image extends \Temma\Web\Controller {
    public function show(string $name) {
        $path = "/var/data/images/$name";
        $this->_contentType(str_ends_with($name, '.png') ? 'image/png' : 'image/jpeg');
        $this['data'] = file_get_contents($path);
    }
}

7Setting default HTTP headers

In the etc/temma.php configuration file, you can specify the HTTP headers to be sent with each response, by listing them with the default key in the x-headers extended configuration. They can be written as key-value pairs or as strings containing the header name and its value:

<?php

return [
    'x-headers' => [
        // default HTTP headers
        'default' => [
            'Cache-Control' => 'no-cache',
            'Sec-Purpose: prefetch',
        ]
    ]
];

These headers are sent after the Content-Type header and the generic cache-disabling headers, and before the specific headers defined with the _header() method (see the previous section).