gowebgo-html-templatego-http

Displaying a pagination widget in Go


I am using HTML templating in Go to render a pagination widget. I am trying to follow an example of how to do it from here: https://www.solodev.com/blog/web-design/adding-pagination-to-your-website.stml

This is my code so far:

// Item size like call 2 item from database
var pagesize = 2
var PaginationSize int = 6
var isActive string
Pagination := make([]int, PaginationSize)

for i := 0; i < PaginationSize; i++ {
    if RequestPageNumber <= page {
        Pagination[i] = i + 1
    } else {
        Pagination[i] = RequestPageNumber + i
    }

    if i == 0 {
        isActive = " active"
    } else {
        isActive = ""
    }
    Info.Pagination += template.HTML(
        fmt.Sprintf(`<li class="page-item%s"><a class="page-link" href=?id=%v>%v</a></li>`,
            isActive, RequestPageNumber+i, RequestPageNumber+i))
}

I would like to improve this by making the pagination list update only when the active page becomes a multiple of PaginationSize. For example, when the displayed pagination shows

(1), 2, 3, 4, 5, 6

If the user clicks on 2, I would like to see

1, (2), 3, 4, 5, 6

But my current code displays

(2), 3, 4, 5, 6, 7

After the page has advanced past 6, the page list should look like

7, 8, 9, 10, 11, 12 ,13 ,14

The data wrapped in this pagination view may be in a database, so I'd also appreciate tips on how to make this work with a database, if possible.

Thanks.


Solution

  • Check next solution

    package main
    
    import (
        "fmt"
    )
    
    const PSIZE = 5
    
    func pager(pageNo int) {
        var start int = pageNo/(PSIZE-1)*(PSIZE-1) + 1
        if pageNo%(PSIZE-1) == 0 {
            start -= PSIZE - 1
        }
    
        for i := start; i < start+PSIZE; i++ {
            if i == pageNo {
                fmt.Printf("(%d) ", i)
            } else {
                fmt.Printf("%d ", i)
            }
        }
        fmt.Print("\n")
    }
    
    func main() {
        pager(4)
        pager(8)
        pager(9)
    }
    

    Output

    1 2 3 (4) 5 
    5 6 7 (8) 9 
    (9) 10 11 12 13 
    

    https://play.golang.org/p/rFslGe2OE0k