Hi there,

Today, I will share you a tips how to rendering view into variable:

To render a template in Phalcon, use the render, getRenderLevel or partial, for example

     //Setting views directory
     $view = new Phalcon\Mvc\View();
     $view->setViewsDir('app/views/');
     $view->start();
     //Shows recent posts view (app/views/posts/recent.phtml)
     $view->render('posts', 'recent');
     $view->finish();

     //Printing views output
     echo $view->getContent();

If the template needs variables to generate its contents, pass them as an array using the second optional argument:

    $parmas = ['vote' => something];
    $this->view->getRender(
        'paritals ', //directory in views
        'comment', //the file into directory paratials
        $params,
        function ($view) {
            $view->setRenderLevel(View::LEVEL_LAYOUT);
        }
    );

    return $this->view->getContent();

Variables passed to a template can be strings, arrays or even objects. Volt abstracts the difference between them and lets you access "attributes" of a variable with the dot (.) notation. The following code listing shows how to display the content of a variable passed by the controller depending on its type:

{# 1. Simple variables #}
{# $this->partial('template', array(
       'name' => 'Phalcon PHP')
   ) #}
{{ name }}

{# 2. Arrays #}
{# $this->partial('template', array(
       'user' => array('name' => 'Phanbook'))
   ) #}
{{ user.name }}

{# alternative syntax for arrays #}
{{ user['name'] }}

{# 3. Objects #}
{# $this->partial('template', array(
       'user' => new User('Phalcontip'))
   ) #}
{{ user.name }}
{{ user.getName }}

{# alternative syntax for objects #}
{{ user.name() }}
{{ user.getName() }}

It is often useful in case a ajax, for example you can see at phanbook or here

Also you can see documents at https://docs.phalconphp.com/en/master/api/Phalcon_Mvc_View.html. Did you enjoy this article? Let us know your thoughts!