View attribute

1Presentation

Temma provides an attribute for specifying the view used by a controller in general and/or by one or more actions in particular.


2Parameter

The attribute takes a single optional parameter, which is the name of the view object to use.

This parameter can be empty or null, in which case the defaultView value from the etc/temma.php file is used (if this value is not defined, the Smarty view is used).

The parameter can also be set to false, which disables the use of the view.

If the string passed as a parameter begins with the tilde character (~), this means that the rest of the string contains the name of a standard view provided by Temma. The prefix \Temma\Views\ will then be added.
For example: ~Json will be interpreted as \Temma\Views\Json


3Examples

For all controller actions to use the JSON view:

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

#[TµView('~Json')]
class MyController extends \Temma\Web\Controller {
    // ...
}

To have a specific action use the RSS view (other actions use the default view, as usual):

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

class MyController extends \Temma\Web\Controller {
    #[TµView('~Rss')]
    public function myAction() {
        // ...
    }
}

So that all actions use the Json view, except for one specific action which uses the RSS view, and another which uses the default view:

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

#[TµView('~Json')]
class MyController extends \Temma\Web\Controller {
    // this action uses the JSON view
    public function firstAction() {
        // ...
    }

    // this action uses the JSON view too
    public function secondAction() {
        // ...
    }

    // this action uses the RSS view
    #[TµView('~Rss)]
    public function thirdAction() {
        // ...
    }

    // this action uses the default view
    #[TµView]
    public function fourthAction() {
        // ...
    }
}

To ensure that no view is used for an action:

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

class MyController extends \Temma\Web\Controller {
    // no view is executed after this action
    #[TµView(false)]
    public function sayHello() {
        print('Hello');
    }
}

4Conditional view

If the view to be used cannot be determined in advance, use the controller's _view() method to define the view:

class MyController extends \Temma\Web\Controller {
    public function myAction() {
        if ($this['responseType'] == 'api') {
            $this->_view('~Json');
        }
        // ...
    }
}

It is of course possible to mix the attribute and the _view() method:

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

#[TµView('~Json')]
class MyController extends \Temma\Web\Controller {
    public function myAction() {
        if ($this['must_use_smarty'] == true) {
            $this->_view('~Smarty');
        }
        // ...
    }
}