Views

Views represent the user interface, they can be web pages or page fragments rendered by controllers or be embedded within other views.

Views are located in Views directory of appropriate module and simply a .php files.

In the most cases, you need to split your page to several parts in order to use them flexible, so you will need some layout that keeps your view fragments together. In order to set a layout, in your controller you can do it like so:


$this->setLayout('layouts/landing');

        

To render a view, you will use render() method like this, which will render the `page.php` file inside Views directory of same module, but if will not find the file in there, then will try to load it from base\views directory:


$this->render('page');

        

In order to send data to view, you will need to pass it as a second argument to the render() method


$this->render('page', [
        'title' => 'The page title', 
        'content' => 'The page content'
]);

        

That the render() method is not outputing the content, you need to call view() helper function to get it.


<section>
    echo view();
</section>

        

When you need output the content immediately use output() method, it's also accpets the view file name as first argument and the data as a second argument:


    $this->output('partials/article', ['text' => 'Some text']);

        

The output() method can be used in view files to embed other view fragments into it.

The data that passed via methods render() and output() are available to that view and not in layout. In such situations there is a method called share() that can be used before rendering a view:


    $this->share(['category' => 'General', 'page' => 'Overview']);

        

The variables become available in layout same way as in views and can be accessed like this:


    <p><?php echo $category ?></p>

        
Template engine

The default renderer of the Quantum framework renders views, where you can write PHP code pieces to `echo` out the variables, write loops and conditional statements. However if you like to use templates, the Quantum has Twig template engine integrated, which makes it easy to compose you views write statments, etc.

To start using the Twig tempalte engine, there are several config parameters need to be added in config.php file.


return array(
    'template_engine' => [
        'twig' => [
            'autoescape' => FALSE,
            'cache' => FALSE,
            'debug' => FALSE,
        ]
    ]
);

        

Once configurations are in there you can now use variables as bellow, make sure you are not placing $ sign at the front of variable name:


    <p>{{ category }}</p>

        

Please refer to Twig documentation to read more about other useful features like loops, statements, etc.

<< Prev Next >>