DRY out this range?

Is there any way I can simplify this range a bit?

I have a menu with 12 items. The first two are “Full Height, Full Width”, the next 8 are “half height, half width”, the last two are “half-height, full width”

I don’t have a public repo I can share, but here’s the code I’ve got. It does exactly what I want, but I’m just curious if it could be simplified any:

<div class="home-table" style="--card-background-url: url({{ $image.RelPermalink }});">
	{{ range first 2 $menu }}
		<div class="card-full">
			<a href="{{ .URL }}">
				{{ .Name }}
			</a>
		</div>
	{{ end }}
	{{ range first 8 (after 2 $menu) }}
		<div class="card">
			<a href="{{ .URL }}">
				{{ .Name }}
			</a>
		</div>
	{{ end }}
	{{ range last 2 $menu }}
		<div class="card-wide">
			<a href="{{ .URL }}">
				{{ .Name }}
			</a>
		</div>
	{{ end }}
</div>

Menus can have params. How about adding the class into params.class?

1 Like
{{ range $k, $v := site.Menus.main }}
  {{ $class := "card" }}
  {{ if lt $k 2 }}
    {{ $class = "card-full" }}
  {{ else if gt $k 9 }}
    {{ $class = "card-wide" }}
  {{ end }}
  <div class="{{ $class }}">
    <a href="{{ .URL }}">{{ .Name }}</a>
  </div>
{{ end }}

But if you add a 13th menu item (never a good idea) the last 3 will be wide. So maybe this instead:

{{ range $k, $v := site.Menus.main }}
  {{ $class := "card" }}
  {{ if lt $k 2 }}
    {{ $class = "card-full" }}
  {{ else if gt $k (sub (len site.Menus.main) 3) }}
    {{ $class = "card-wide" }}
  {{ end }}
  <div class="{{ $class }}">
    <a href="{{ .URL }}">{{ .Name }}</a>
  </div>
{{ end }}
2 Likes

Thanks this is exactly what I was looking for. Works perfect, and makes sense to me!

1 Like

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