Reputation: 5262
How can I pass variables to main view, not just the view for controller.
in fact I want to share a piece of data across all views. how can I do that in phalcon.
for instance, in Laravel, I can use:
View::share('variable', $value);
Upvotes: 4
Views: 6483
Reputation: 2153
I think better would be to create BaseController - parent controller everyone extends. And then using event add shared data to view after execution of each action:
<?php
class ControllerBase extends \Phalcon\Mvc\Controller
{
protected $_sharedData = [];
public function initialize()
{
// set shared data for all actions
this->_sharedData = [
'sharedVar' = 1,
'overrideMe' = false
];
}
public function afterExecuteRoute($dispatcher)
{
// Executed after every found action
$this->view->setVar('sharedData', $this->_sharedData);
}
}
In child controller
<?php
class IndexController extends ControllerBase
{
public function initialize()
{
parent::initialize();
// override shared variable for all Index actions
$this->_sharedData['overrideMe'] = true;
}
public function homeAction()
{
// add custom variable to shared data
$this->_sharedData['customVar'] = -1;
}
}
Upvotes: 3
Reputation: 2465
You could create a service for that - if this is simple variable it will be an overkill but it will work.
<?php
// In your bootstrap file
$di->setShared('variable', 41);
?>
Then in any view (or a controller or any DI injectable) it will be avaiable as $this->variable
. Ie:
// some view
<?php echo $this->variable; ?>
// or using volt
{{ variable }}
The variable of course can be an object. Personally for such simple variables I'm using config object, ie: {{ config.facebook.fbId }}
.
Upvotes: 3
Reputation: 1700
With Phalcon you don't need any additional functions to pass data into the layout. All variables assigned in the action are available in the layout automatically:
Controller:
class IndexController extends \Phalcon\Mvc\Controller
{
public function indexAction()
{
$this->view->bg = 'green';
$this->view->hello = 'world';
}
}
Main layout:
<html>
<body style="background: <?php echo $bg ?>">
<?php echo $this->getContent(); ?>
</body>
</html>
Action view:
<div>
<?php echo $hello ?>
</div>
You will see text 'world' on the green background.
Upvotes: 4