How to render a view with variable

Aug '15

Oct '17




edited Aug '15
Aug '15

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();
     //Shows recent posts view (app/views/posts/recent.phtml)
     $view->render('posts', 'recent');

     //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];
        'paritals ', //directory in views
        'comment', //the file into directory paratials
        function ($view) {

    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'))
   ) #}
{{ }}

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

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

{# alternative syntax for objects #}
{{ }}
{{ 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 Did you enjoy this article? Let us know your thoughts!

edited Oct '17
Oct '17

Khi dùng getRender thì nó chỉ render chính view mình sét, ví dụ: Mình muốn gửi mail html format với template = email.volt $this->view->getRender('dir_email', 'email', $parameters)

khi nó chạy chỉ render mỗi email.volt mà tất cả các view khác đều stop hết. ( chả hiểu là sao nữa nhiều người bị và phải chuyển sang $view->render()). Bất tiện ở chỗ vì nó khi run phát nó disable hết các view nên return blank page và không có một thông báo lỗi nào cả.