ProcessWire Repeater字段带有层级数据输出

按照官方的示例:

$depth = -1;
foreach($page->repeater_items as $item) {
  if($item->depth > $depth) {
    echo "<ul>";
  } else if($item->depth < $depth) {
    echo "</ul>";
  }
  echo "<li>$item->title";
  $depth = $item->depth;
}
while($depth--) echo "</ul>";

会得到一个这样的效果

但是这里我发现有些问题,如果要控制子菜单样式会有很多问题,于是我改良了一下(以bootstrap的菜单为例):

$depth = -1;
if(isset($home->builder->get("type=menu")->links)){

	foreach($home->builder->get("type=menu, componentInfo.id=header")->links as $menu) {
	  $item = $menu->link;


	  if($menu->depth > $depth) {
	  	$isSub = ($menu->depth > 0) ? ' class="submenu"' : '';
	    echo "<ul{$isSub}>";
	  } else if($menu->depth < $depth) {
	    echo "</ul></li>";
	  }

	  //var_dump($page->path . ' = ' . $item->url . ' = ' . $page->parent->path);
	  $active = ($page->path == $item->url || $page->parent->path == $item->url) ? " active" : "";

	  if($page !== $home && $item->url == "/"){
	  	$active = "";
	  }

	  $class = ($menu->depth == 0) ? " class='{$active}'" : "";
	  $isParent = (isset($menu->depth) && $menu->depth == 0  && $menu->next->depth == ($menu->depth + 1)) ? true : false;	//$item->prev->depth == 0

	  if($isParent){
	  	echo "<li class='has-dropdown'><a href='{$urlPrefix}{$item->url}'{$class}><span>{$item->name}</span> <i class='bi bi-chevron-down'></i></a>";
	  }else{
	  	echo "<li><a href='{$urlPrefix}{$item->url}'{$class}>{$item->name}</a></li>";
	  }

	  $depth = $menu->depth;
	  
	}
	echo "</ul>";
}

Post Comment