I have simple application in zf2, I have menu in layout which is for each page of application. e.g., provinces/index.phtml, districts/index.phtml, cities/index.phtml etc.
Menu is:
<li class="start active ">
<a href="admin">
<i class="fa fa-home"></i>
<span class="title">
Dashboard
</span>
<span class="selected">
</span>
</a>
</li>
<li>
<a href="provinces">
<i class="fa fa-globe"></i>
<span class="title">
Provinces
</span>
</a>
</li>
<li>
<a href="districts">
<i class="fa fa-map-marker"></i>
<span class="title">
Districts
</span>
</a>
</li>
<li>
<a href="cities">
<i class="fa fa-tint"></i>
<span class="title">
Cities
</span>
</a>
</li>
I have code:
<div class="page-content-wrapper">
<?php echo $this->content; ?> <!--this print contents of index.phtml -->
</div>
which access each page in the same layout.
Now I want to make menu dynamically, i.e., when provinces is selected then provinces should highlighted, if districts is selected then districts in menu should be highlighted.
I tried the logic like below: In provinces/index.phtml I write the code $selected_page="provinces", in districts/index.phtml I write the code $selected_page="districts" etc
Then in menu in layout:
I write class="start active" >
same is for districts and provinces etc.
But here variable $selected_page can not accessed, because
<?php echo $this->content; ?>
can only print and display content of index.phtml, and variable is not passed to layout. So how should I do this? how should I pass variable $current_page to layout, or show me other logic about it.
Thanks in advance:
If you want to pass variable from controller/action (for example provincesAction()
) to view. Use layout()
controller plugin:
public function provincesAction()
{
$this->layout()->setVariable('foo', 'bar');
return new ViewModel([]);
}
In layout.phtml
// html code
<?php echo $this->foo; ?> // It will display "bar"
// more html code
But for your example. I would suggest you to use navigation()
view helper. Read more on https://framework.zend.com/manual/2.4/en/modules/zend.navigation.view.helper.menu.html. This plugin is made just for such things like you need.