Answer the question
In order to leave comments, you need to log in
How to display a multi-level menu in a view. Yii2?
I am making a website using the Yii2 course from webformyself. And I ran into such a problem that it is not possible to display a multi-level menu.
Here is the controller:
<?php
namespace app\components;
use yii\base\Widget;
use app\models\Category;
use Yii;
class MenuWidget extends Widget
{
public $tpl;
public $model;
public $data;
public $tree;
public $menuHtml;
public function init()
{
parent::init();
if( $this->tpl === null ) {
$this->tpl = 'menu';
}
$this->tpl .= '.php';
}
public function run()
{
// get cache
if($this->tpl == 'menu.php') {
$menu = Yii::$app->cache->get('mainMenu'); //кэширование
if($menu) return $menu;
}
$this->data = Category::find()->indexBy('category_id')->asArray()->all();
$this->tree = $this->getTree();
$this->menuHtml = $this->getMenuHtml($this->tree);
//set cache
if($this->tpl === null ) {
Yii::$app->cache->set('mainMenu', $this->menuHtml, 60); //кэширование
}
return $this->menuHtml;
}
protected function getTree()
{
$tree = [];
foreach ($this->data as $id=>&$node) {
if (!$node['parent_id'])
$tree[$id] = &$node;
else
$this->data[$node['parent_id']]['childs'][$node['category_id']] = &$node;
}
return $tree;
}
protected function getMenuHtml($tree, $tab = '')
{
$str = '';
foreach ($tree as $category) {
$str .= $this->catToTemplate($category, $tab);
}
return $str;
}
protected function catToTemplate($category, $tab)
{
ob_start();
include __DIR__ . '/menu_tpl/' . $this->tpl;
return ob_get_clean();
}
}
<li>
<a href="<?= \yii\helpers\Url::to(['category/view', 'id' => $category['id']]) ?>" id="mainMenu">
<?= $category['name']?>
</a>
<?php if(isset($category['childs']) ): ?>
<ul class="subMainMenu">
<?=$this->getMenuHtml($category['childs'])?>
</ul>
<?php endif;?>
</li>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question