我正在尝试从类别表创建Phalcon框架中的多级菜单。到目前为止,我做到了这一点:
MySql表类别:
id parent name count_post
1 0 level_1_name_1 0
2 1 level_2_name_2 0
3 1 level_2_name_3 0
4 2 level_3_name_4 60
5 2 level_3_name_5 30
6 0 level_1_name_6 0
7 6 level_2_name_7 0
8 6 level_2_name_8 0
9 7 level_3_name_9 80
10 7 level_3_name_10 90
我需要创建一个这样的html:
<ul>
<li>
<a>level_1_name_1</a>
<ul>
<li>
<a>level_2_name_2</a>
<ul>
<li><a>level_3_name_4</a></li>
<li><a>level_3_name_5</a></li>
</ul>
</li>
<li>
<a>level_2_name_3</a>
</li>
</ul>
</li>
<li>
<a>level_1_name_6</a>
<ul>
<li>
<a>level_2_name_7</a>
<ul>
<li><a>level_3_name_9</a></li>
<li><a>level_3_name_10</a></li>
</ul>
</li>
<li>
<a>level_2_name_8</a>
</li>
</ul>
</li>
</ul>
在控制器中我从模型中获取数据:
$menu = Menu::find();
$this->view->setVar('menu', $menu);
但是如何在伏特模板中生成HTML以输出如上所述?谢谢你的帮助!
答案 0 :(得分:2)
这样的事可能适合你:
class Menu extends ModelBase
{
public $id;
public $parent;
public $name;
public $count_post;
public function getChilds()
{
$result = false;
if($this->id) {
$childs = self::find("parent = $this->id");
if(count($childs)) {
$result = $childs;
}
}
return $result;
}
}
{%- macro print_menu_level(menu_level_items) %}
{%- for menu_item in menu_level_items %}
{% if loop.first %}
<ul>
{% endif %}
<li>
<a>{{ menu_item.name }}</a>
{% set next_menu_level_items = menu_item.getChilds() %}
{% if next_menu_level_items %}
{{ print_menu_level(next_menu_level_items) }}
{% endif %}
</li>
{% if loop.last %}
</ul>
{% endif %}
{%- endfor %}
{%- endmacro %}
{{ print_menu_level(root_menu_items) }}
$rootMenuItems = Menu::find('parent = 0');
$this->view->setVar('root_menu_items', $rootMenuItems);
免责声明:这只是我没有测试过的一个例子_