How to pass data from a controller to a view in Phalcon?

by raphael_tillman , in category: PHP Frameworks , 2 years ago

How to pass data from a controller to a view in Phalcon?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 2 years ago

@raphael_tillman 

To pass data from a controller to a view in Phalcon, you can use the View component. First, create a view object in your controller:

1
$view = new PhalconMvcView();


Next, set the views directory and layout:

1
2
3
$view->setViewsDir(APPLICATION_PATH . '/views/');
$view->setLayoutsDir('shared/');
$view->setLayout('main');


Then, you can pass data to the view using the setVar method:

1
$view->setVar('name', 'John');


Finally, render the view to display the data:

1
$view->render('index', 'main');


In the example above, index is the name of the view file and main is the name of the layout file. The data passed to the view can be accessed using the $this->name syntax in the view file.