View Single Post
  #1  
Old 06-22-2017, 02:53 AM
 
xgarb xgarb is offline
 

eXpert
  
Join Date: Jul 2004
Location: UK
Posts: 263
 

Default Side Menu with less HTML in the page

On our site we have a side menu that looks like this:




This menu (based on the flyout menu I think) is created by taking the whole category structure, creating HTML from this and then hiding via CSS the parts that shouldn't be shown. This means that there is superfluous HTML in the code. We have a lot of categories and depth so that's a lot of HTML!

So.. I've tried to recode the menu but rather than starting with the whole category structure, I take the path of the current location and then add in the siblings of each level to make my array.

Code:
/** * Output menu tree based on path * * @return string */ protected function makeMenuFromCurrentCatID() { $categoryPath = \XLite\Core\Database::getRepo('\XLite\Model\Category')-> getCategoryPath($this->getCategoryId()); // from https://stackoverflow.com/questions/44507936/create-multidimensional-array-from-four-arrays-based-on-parent-id/44522606 $tree = []; $parent = &$tree; // Use `= &` to reference the same location foreach ($categoryPath as $category) { $currentCatSiblings = $category->getSiblings(true); foreach ($currentCatSiblings as $sibling) { $parent[$sibling->getID()] = []; } $parent = &$parent[$category->getID()]; // Use `= &` to reference the deeper location } return $tree; }

Which is used with this twig code

Code:
<ul class="sidemenu menu-tree catalog-categories catalog-categories-tree"> {% for first, firstitems in this.makeMenuFromCurrentCatID() %} <li class="leaf"><a class="topcat" href="{{ this.getCatLinkFromID(first) }}">{{ this.getCatNameFromID(first) }}</a> {% if firstitems is not empty %} <ul class="sidemenu menu-tree sublevel"> {% for second, seconditems in firstitems %} <li><a {{ this.isActiveCategory(second) }} href="{{ this.getCatLinkFromID(second) }}">{{ this.getCatNameFromID(second) }}</a> {% if seconditems is not empty %} <ul class="sidemenu menu-tree sublevel"> {% for third, thirditems in seconditems %} <li><a {{ this.isActiveCategory(third) }} href="{{ this.getCatLinkFromID(third) }}">{{ this.getCatNameFromID(third) }}</a> {% if thirditems is not empty %} <ul class="sidemenu menu-tree sublevel"> {% for fourth, fourthitems in thirditems %} <li><a {{ this.isActiveCategory(fourth) }} href="{{ this.getCatLinkFromID(fourth) }}">{{ this.getCatNameFromID(fourth) }}</a></li> {% endfor %} </ul> {% endif %} </li> {% endfor %} </ul> {% endif %} </li> {% endfor %} </ul> {% endif %} </li> {% endfor %} </ul>

Which all works. However.. I have some questions that I'll put in subsequent posts to keep this readable.
__________________
Core version: 5.5.xx
Reply With Quote