Cropped Pagination Controls With Hugo
I’m currently in the middle of migrating my blog (yet again) from Hexo to Hugo . Hexo is nice but I’m learning some HTML/CSS and decided to give Hugo a try and I liked the following about it
-
Setting it up is just a matter of downloading a single EXE file and adding it to PATH, as opposed to having to install NodeJS, then Hexo
-
Shortcodes are part of the theme, not a plugin
-
Go themes are close enough to Jinja2 which I have been using for a couple of years now with Salt and Ansible
-
In general, Hugo is easier to maintain in git as the whole folder can be tracked, whereas with Hexo, the node_modules folder needs to be in .gitignore
-
Hugo supports multiple categories per post, whereas Hexo doesn’t
Unlike Hexo, the default pagination in Hugo doesn’t react well to having lots of pages. _internal/pagination.html will print all pages even if you have hundreds.
Just use the following code to handle the scenario
1{{ $pag := .Paginate (where .Data.Pages "Type" "post") }}
2{{ $first := sub $pag.PageNumber 4 }}
3{{ $last := add $pag.PageNumber 4 }}
4<div class="block">
5 <ul class="pagination" style="white-space:nowrap;">
6 {{ if $pag.HasPrev }}
7 <li><a href="{{ $pag.First.URL }}">«First</a></li>
8 <li><a href="{{ $pag.Prev.URL }}">«Prev</a></li>
9 {{ end }}
10
11 <li {{ if not $pag.HasPrev }}class="active"{{ end }}><a href="{{ $pag.First.URL }}">1</a></li>
12 {{ if gt $first 2 }}
13 <li>...</li>
14 {{ end }}
15
16 {{ range $pag.Pagers }}
17 {{ if and (gt .PageNumber 1) (ge .PageNumber $first) (lt .PageNumber $last) (lt .PageNumber $pag.TotalPages) }}
18 <li {{ if eq . $pag }}class="active"{{ end }}><a href="{{ .URL }}">{{ .PageNumber }}</a></li>
19 {{ end }}
20 {{ end }}
21
22 {{ if lt $last $pag.TotalPages }}
23 <li>...</li>
24 {{ end }}
25 <li {{ if not $pag.HasNext }}class="active"{{ end }}><a href="{{ $pag.Last.URL }}">{{ $pag.TotalPages }}</a></li>
26
27 {{ if $pag.HasNext }}
28 <li><a href="{{ $pag.Next.URL }}">Next »</a></li>
29 <li><a href="{{ $pag.Last.URL }}">Last »</a></li>
30 {{ end }}
31 </ul>
32</div>
About Me
Dev gone Ops gone DevOps. Any views expressed on this blog are mine alone and do not necessarily reflect the views of my employer.
Recent Posts