{% assign page_url_path = url | regexReplace: '/index$|/index\.html$|\.html$|/$' -%}
{% assign active_entries = nav | activeNavEntryIndexArray: page_url_path -%}

<ul class="nav flex-column">
  {%- for entry in nav -%}
    {% if entry == 'divider' -%}
      <li aria-hidden="true"><div class="sidebar-primary-divider"></div></li>
    {% elsif entry contains 'header' -%}
      <li class="nav-header">{{entry.header}}</li>
    {% else -%}
      {% assign id = 'sidenav-' | append: forloop.index -%}
      {% if forloop.index == active_entries[0] -%}
        {% assign isActive = true -%}
        {% assign class = 'active' -%}
      {% else -%}
        {% assign isActive = false -%}
        {% assign class = '' -%}
      {% endif -%}
      {% if entry.children -%}
        {% if isActive or entry.expanded -%}
          {% assign expanded = 'true' -%}
          {% assign show = 'show' -%}
        {% else -%}
          {% assign class = 'collapsed' -%}
          {% assign expanded = 'false' -%}
          {% assign show = '' -%}
        {% endif -%}
        <li class="nav-item">
          <a class="nav-link {{class}} collapsible" data-toggle="collapse" href="#{{id}}" role="button" aria-expanded="{{expanded}}" aria-controls="{{id}}">{{entry.title}}</a>
      
          <ul class="nav flex-column flex-nowrap collapse {{show}}" id="{{id}}">
            {% if isActive -%}
            {%- render 'sidenav-level-2.html', parent_id:id, children:entry.children, active_entries:active_entries -%}
            {% else -%}
            {%- render 'sidenav-level-2.html', parent_id:id, children:entry.children -%}
            {% endif -%}
          </ul>
        </li>
      {%- elsif entry.permalink -%}
        {% if entry.permalink contains '://' -%}
        {% assign isExternal = true -%}
        {% else -%}
        {% assign isExternal = false -%}
        {% endif -%}
        <li class="nav-item">
          <a class="nav-link {{class}}" href="{{entry.permalink}}"
             {%- if isExternal %} target="_blank" rel="noopener" {%- endif -%}>
            {{entry.title}}
          </a>
        </li>
      {% endif -%}
    {% endif -%}
  {%- endfor -%}
</ul>
