【问题标题】:How to use templates in Go Gin for dynamic content如何在 Go Gin 中使用模板获取动态内容
【发布时间】:2016-10-15 05:57:30
【问题描述】:

我有一个简单的 Go / Gin 网络应用程序。我需要在 html 模板中添加一些动态内容。

例如我有几张表(数字是动态的)和几行(数字是动态的)。我需要将它们放在 html 模板中。有没有办法在代码中组合模板?我更喜欢使用模板而不是在代码中构建表格。

我查看了一个教程https://github.com/gin-gonic/gin,但那里没有介绍。

【问题讨论】:

    标签: go go-templates go-gin


    【解决方案1】:

    您可以使用define 定义分部,并使用template 混合多个HTML 分部。

    package main
    
    import (
        "html/template"
    
        "github.com/gin-gonic/gin"
    )
    
    var (
        partial1 = `{{define "elm1"}}<div>element1</div>{{end}}`
        partial2 = `{{define "elm2"}}<div>element2</div>{{end}}`
        body     = `{{template "elm1"}}{{template "elm2"}}`
    )
    
    func main() {
        // Or use `ParseFiles` to parse tmpl files instead 
        t := template.Must(template.New("elements").Parse(body))
    
        app := gin.Default()
        app.GET("/", func(c *gin.Context) {
            c.HTML(200, "elements", nil)
        })
        app.Run(":8000")
    }
    

    这是阅读https://gohugo.io/templates/go-templates/的好地方

    【讨论】:

    • 谢谢!这个资源真的很有用。
    • 另一个有用的资源是golang.org/pkg/text/template——这是模板的官方文档。它没有@pie-oh-pah 发布的那么好,但至少很清楚什么是“官方”文档的一部分,以及Hugo 的具体内容。
    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 2020-03-16
    相关资源
    最近更新 更多