我在数组中有下一个数据结构。
$a = [['id' => 1, 'parent_id' => 0], ['id' => 2, 'parent_id' => 0], ['id' => 3, 'parent_id' => 2], ['id' => 4, 'parent_id' => 3]];
我有所有主要类别的水平菜单('parent_id'= 0)。 下一个代码将打印所有主要类别。
{% for dept in common.departments %}
{% if dept.parent_id == 0 %}
<li><a href="/{{ dept.seo_title }}/{{ dept.id }}/dept" class="black">{{ dept.title }}</a><!-- for subdepartments --></li>
{% endif %}
{% endfor %}
如何以树格式打印所有子类别?
示例:
Dept 1 Dept4
Dept5 Dept2
Dept7 Dept3
更改:
<div class="clearfix">
{% macro displayChildren(departments, parent_id, deep) %}
{% for dept in departments %}
{% if dept.parent_id == parent_id %}
<li><a href="/{{ dept.seo_title }}/{{ dept.id }}/dept" class="black" style="margin-left: {{ deep * 10 }}px;">{{ dept.title }}</a></li>
{{ _self.displayChildren(departments, dept.id, deep + 1) }}
{% endif %}
{% endfor %}
{% endmacro %}
{% for dept in common.departments %}
{% if (dept.parent_id == 0) %}
<li><a href="/{{ dept.seo_title }}/{{ dept.id }}/dept" class="black">{{ dept.title }}</a><div class="dropdown-menu"><ol class="nav">{{ _self.displayChildren(common.departments, dept.id, 0) }}</ol></div></li>
{% endif %}
{% endfor %}
</div>
答案 0 :(得分:2)
使用宏和递归应该有效:
{{ _self.displayChildren(departments, 0, 0, '') }}
{% macro displayChildren(departments, parent_id, deep, concat) %}
{% for dept in departments %}
{%- if dept.parent_id == parent_id %}
{% set subconcat = (concat ? concat ~ '-':'') ~ 'dept' ~ dept.id %}
{{ subconcat }}
{{ _self.displayChildren(departments, dept.id, deep + 1, subconcat) }}
{% endif -%}
{% endfor %}
{% endmacro %}
显示:
<div style="margin-left: 0px;">dept1</div>
<div style="margin-left: 0px;">dept2</div>
<div style="margin-left: 20px;">dept2-dept3</div>
<div style="margin-left: 40px;">dept2-dept3-dept4</div>
或解释: