Saturday 23 December 2017

Dynamic Multi-Level Menu: Sitecore

multi-level-menu-sitecore
Dynamic Multi-level Menu

Requirements:
Here's a requirement where someone asking to create multi-level menu, but the condition is in future client can add more submenu level. It means unlimited level of navigation.

Resources:
With the help of controller will able to get the list of navigation item from sitecore content tree. And if in future, if someone going to add more navigation item then no need to change code logic.

Implementation:
Now at the time of rendering, we wanted to list all the navigation item with less-code smartly. Previously we were listing navitem like:
<div>
   <ul>
     @if (Model?.Items != null)
     {
            foreach (var item in Model.Items)
           {
               var hasChildren = item.Children != null && item.Children.Items.Any();
       if (hasChildren)
       {
                 <li>
                    foreach(var subitem in item)
       {
                      //again repeating above logic
       }
                </li>
       }
       else
       {
                //render logic
       }
          }
      }
</ul>
 </div>

but here we are limiting the multi-level menu, like as much as sub-items level that much time we are going to add foreach() logic. And If In future clients going to add one more sub navigation item with new level then it may impact to the application.

To outcome with this problem,

found magical component: @helper

@helper is:
  • resuable component
  • include code and markup both
  • easier to read
  • can call recursivly once write logic, even in the markup file.
  • can declare and define both in the view, to reduce complexity of the code.

Below is the code sample to write dynamic multi-level menu logic:

<div>
     <ul>
       @if (Model?.Items != null)
{
               @NavItems(Model.Items);
}
     </ul>
</div>

@helper NavItems(List<item> Items)
{
foreach (var item in Items)
 {
   var hasChildren = item.Children != null && item.Children.Items.Any();
   if (hasChildren)
   {
      <li>
         @NavItems(item);
      </li>
   }
   else
  {
      //render logic
   }
}
}

Above code are only for reference, please let me know if any query.


Have a Good Day.

No comments:

Post a Comment