du548397507 2016-06-14 13:11
浏览 765
已采纳

如何在Go Gin中使用模板获取动态内容

I have a simple Go / Gin web app. I need to put some dynamic content in html template.

For e.g. I have a few tables (the number is dynamic) with a few rows (the number is dynamic). I need to put them in html template. Is there any way to combine templates in code? I'd prefer to use templates rather than build tables in the code.

I've checked a tutorial https://github.com/gin-gonic/gin but it is not covered there.

  • 写回答

1条回答 默认 最新

  • douwo5710 2016-06-14 14:06
    关注

    You can use define to define partials and template to mix multiple HTML partials.

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

    This is a good place to read https://gohugo.io/templates/go-templates/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog