I'm trying to create a html template for displaying posts via html/template
Go package. I also want to make pagination on my page, to display 5 posts per page.
So I take the post count from my post repository, dividing it by posts per page value and rounding it (ceil). That's the total number of pages with posts currently available.
I pass the total number of pages to my html template. Now, in my html template I need to display page buttons from 1 to the total number.
In the text/html
package there is an awesome documentation about how to work with pipelines, but I didn't find any example of creating simple loop.
I got the solution, but I am not sure it is the good one. I can pass to template not just the total number of pages, but an array of available pages, so in my template I can do something like:
{{range .pages}}
<div class="page"><a href="/posts/{{.}}">{{.}}</a></div>
{{end}}
But maybe there is a better way to do this than passing an array of pages? I also know about possibility of passing custom functions to template. Could it be a solution?
The rule is that the template must contain the minimal logic possible (and that's the reason why the native functions and controls are so limited into the template package).
You should prepare your data into the controller by putting it into a dedicated struct (to be passed to the template). Then you can display this struct (composed of variables and arrays) into the template by using the range function as you intended to do.
try this, i have do my best...
package main
import "html/template"
import "os"
type data struct {
Url string
Title string
}
type show struct {
Pages []data
}
const html = `<html>
{{range .Pages}}
<div class="page"><a href="/posts/{{.Url}}">{{.Title}}</a>
</div>
{{end}}
</html>`
func show_template() {
webpage, _ := template.New("template").Parse(html)
mydata := []data{{
Url: "page-1.html",
Title: "go to page 1",
}, {
Url: "page-2.html",
Title: "go to page 2",
}, {
Url: "page-3.html",
Title: "go to page 3",
}, {
Url: "page-3.html",
Title: "go to page 3",
}}
web_data := show{mydata}
webpage.Execute(os.Stdout, web_data)
}
func main() {
show_template()
}
and this is the result..
<html>
<div class="page"><a href="/posts/page-1.html">go to page 1</a></div>
<div class="page"><a href="/posts/page-2.html">go to page 2</a></div>
<div class="page"><a href="/posts/page-3.html">go to page 3</a></div>
<div class="page"><a href="/posts/page-3.html">go to page 3</a></div>
</html>