【问题标题】:What is the best way of creating loop in go html template?在 go html 模板中创建循环的最佳方法是什么?
【发布时间】:2017-05-21 18:12:37
【问题描述】:

我正在尝试创建一个 html 模板,用于通过 html/template Go 包显示帖子。 我还想在我的页面上进行分页,每页显示 5 个帖子。

所以我从我的帖子存储库中获取帖子计数,将其除以每页的帖子值并四舍五入(ceil)。这是当前可用帖子的总页数。

我将总页数传递给我的 html 模板。 现在,在我的 html 模板中,我需要显示页面按钮从 1 到总数

text/html 包中,有一个关于如何使用管道的很棒的文档,但我没有找到任何创建简单循环的示例。

我得到了解决方案,但我不确定它是否是好的解决方案。 我不仅可以将页面总数传递给模板,还可以传递可用页面的数组,因此在我的模板中我可以执行以下操作:

{{range .pages}}
    <div class="page"><a href="/posts/{{.}}">{{.}}</a></div>
{{end}}

但也许有比传递页面数组更好的方法来做到这一点? 我也知道将自定义函数传递给模板的可能性。有办法解决吗?

【问题讨论】:

  • 我对@9​​87654326@了解不多;有人可能有更好的答案。但测距在我看来是合理的。
  • 这不是一个巨大的节省,可能不值得,但是您可以在定义您的上下文时使用空结构:"pages": make([]struct{}, 16) {{ range $pageNum, $_ := .pages }} 在模板中:play.golang.org/p/jvFp1TptMV。空结构技巧来自github.com/bradfitz/iter/blob/master/iter.go

标签: templates go go-html-template


【解决方案1】:

规则是模板必须包含尽可能少的逻辑(这就是为什么原生函数和控件被限制在模板包中的原因)。

您应该通过将数据放入专用结构(将传递给模板)来将数据准备到控制器中。然后,您可以按照您的意图使用 range 函数将该结构(由变量和数组组成)显示到模板中。

【讨论】:

    【解决方案2】:

    试试这个,我已经尽力了……

    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()
    
    }
    

    这就是结果..

    <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>
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 2020-09-22
      • 2017-04-21
      • 2018-03-21
      • 2010-10-08
      • 2013-10-05
      • 2012-05-18
      • 1970-01-01
      • 2012-01-08
      相关资源
      最近更新 更多