Wrap every 10 <li> in a div

Currently I use the following code code to loop over all category(taxonomy) values in a website:

    <ul>

      {{ range $key, $value := site.Taxonomies.countries }}
        <li>
          <span>
            <a href="{{ .Page.RelPermalink }}">{{$key | humanize}}</a>
          </span>
        </li>
      {{end}}

    </ul>

Now, I wish to wrap every 10 category value within a div. How do I do that ?
Finally I want something like this:


  <ul>
    <div>
     <!-- 10 <li> tags -->
    </div>
    <div>
     <!-- 10 <li> tags -->
    </div>

<!-- So on ... -->
  </ul>

<ul>
  <div>
    {{ $i := 0 }}
    {{ range $key, $value := site.Taxonomies.countries }}
      {{ $i = add $i 1 }}
      <li>
        <span>
          <a href="{{ .Page.RelPermalink }}">{{ $key | humanize }}</a>
        </span>
      </li>
      {{ if modBool $i 10 }}
        </div><div>
      {{ end }}
    {{end}}
  </div>
</ul>
6 Likes

@jmooring Thanks a lot for the solution. I really appreciate that.

Whilst the solution provided by @jmooring is exactly what you asked for, it results in invalid html.

The only permitted content of a <ul> is <li>, <script> or <template>. <ul>: The Unordered List element - HTML: HyperText Markup Language | MDN

What’s the purpose of the <div> exactly? It may make more sense to use pseudo elements, or to create multiple lists. Depends on what you are trying to achieve…

@nternetinspired Thanks for your inputs. My goal was to create a mega menu dropdown, which is basically a menu dropdown with multiple columns.
I wanted each column to have 10 elements maximum.

But I think instead of div I should use only <ul> and <li> to achieve this.

1 Like

Personally I’d use a nested list, somthing liike:

<nav aria-label="main">
  <ul>
    <li>
      <a href="#">Level 1</a>
      <ul>
        <li><a href="#">Level 2</a></li>
        <li><a href="#">Level 2</a></li>
      </ul>
    </li>
    <li>
      <a href="#">Level 1</a>
      <ul>
        <li><a href="#">Level 2</a></li>
        <li><a href="#">Level 2</a></li>
      </ul>
    </li>
  </ul>
</nav>

Alternatively, use a single list and than arrange it into columns with flexbox or grid styles.

1 Like

Hi @nternetinspired . Thanks for your inputs. I like your implementation.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.