In my project I have a number of dynamic elements that are consistently on every page. I have put these in my layout.phtml
My question is: How can I send variables into my layout from my controllers?
If I want to send things from my controller I can use:
$this->view->whatever = "foo";
And receive it in the view with
echo $this->whatever;
I cannot figure out how to do the same with my layout. Perhaps there is a better way around the problem?
The standard view variables are available if you use the layout within the MVC. In bootstrap file, include this:
You must then tell each controller (or even each action, if you wanted granular control over several different layouts) which layout to use. I put mine in the init() of each controller. Here's an example, if your layout file is named layout.phtml:
Without using helpers or plugins do :
After this you can use the following in your layout:
This will print "foo".
View Helpers are also a good idea. I had a ecommerce website, which I had a layout.phtml with menus with categories and subcategories that I needed to bring from the database.
For this, I did the following:
Bootstrap.php:
application.ini:
In views/helpers, I had a file called Menus:
In layout.phtml, I just had to call the specific helper, and call the methods from it:
Hope it helps someone that needs to bring data from database to render the layout.
As a side note, if you send json at some point in your app be careful that global view variables are not sent with the response.
I have a implemented a Base Controller which all other controllers extend.
So I have a controller...
and in the layout and/or view
In the layout file you can call
If in some actions if you don't want that section then: