Php 在细枝模板引擎中打印子类别
我有数组中的下一个数据结构Php 在细枝模板引擎中打印子类别,php,symfony,twig,Php,Symfony,Twig,我有数组中的下一个数据结构 $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.department
$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 %}
更改:
<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>
{%macro-displayChildren(部门,父\u-id,深)%}
{部门%中的部门为%}
{%if dept.parent\u id==parent\u id%}
{{{u self.displayChildren(departments,dept.id,deep+1)}
{%endif%}
{%endfor%}
{%endmacro%}
{common.departments%}
{%if(dept.parent_id==0)%}
{{{u self.displayChildren(common.departments,dept.id,0)}
{%endif%}
{%endfor%}
使用宏和递归应该可以:
{{ _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>
dept1
dept2
dept2-dept3
dept2-dept3-dept4
或解释:
谢谢。我做到了。你真是天才!如何保存seo_标题?我需要搜索引擎优化标题树结构。从最低的子类别到主类别/Subcategory 2-Subcategory 1-maincategory/?哦,好的,然后添加第四个参数,其中包含整个路径的串联。让我编辑。我编辑时没有颠倒顺序。若要反转它,请使用
{{u self.displayChildren(departments,0,0'))| split(“\n”)| reverse | join(\n”)}
而不是第一行。执行了吗。看起来很棒!如果我知道用户选择了某个子部门,是否可以区分所有上级部门?在你的例子中,我可能是dept4。因此,我们需要在dept4链接和所有父链接中添加下划线。Twig可以吗?我允许您向包含基本部门的宏添加第五个参数。然后,将{{subsubcat}}
替换为{%if subsubsubcat[0:basedept | length]==basedept%}{{subsubcat}{%endif%}
,这应该很好。我现在就不多说了,如果需要的话,请提出新的问题。谢谢
<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>