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/

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

报告相同问题?

悬赏问题

  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!