Simplify custom paging

I’m fairly new to Hugo, but trying to learn. I have setup custom paging to show 8 pages at a time in the pagination section, and keep the current page towards the middle, since I have more than 10 pages of content, and so many number icons just looks funny. This code seems to work, but seem extremely hacky and contains duplication. Is there a simpler way of handling it?

                {{ $start := $.Site.Params.Paginate }}
                {{ $halfStart := div $start 2 }}
                {{ $after := sub $pag.PageNumber $halfStart }}

                {{ if le $pag.PageNumber $halfStart }}
                {{ range first $start $pag.Pagers }}
                    {{ if eq . $pag }}
                            <span class="pagecurrent">
                                    {{ .PageNumber }}
                            </span>
                    {{ else }}
                            <span class="displaypageNum">
                                    <a href="{{ .URL }}">{{ .PageNumber }}</a>
                            </span>
                    {{ end }}
                {{ end }}
                {{ else }}
                {{ range first $start (after $after $pag.Pagers) }}
                    {{ if eq . $pag }}
                            <span class="pagecurrent">
                                    {{ .PageNumber }}
                            </span>
                    {{ else }}
                            <span class="displaypageNum">
                                    <a href="{{ .URL }}">{{ .PageNumber }}</a>
                            </span>
                    {{ end }}
                {{ end }}
                {{ end }}