首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Go Gin中使用模板实现动态内容

如何在Go Gin中使用模板实现动态内容
EN

Stack Overflow用户
提问于 2016-06-14 13:11:44
回答 1查看 9K关注 0票数 8

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

例如,我有几个表(数字是动态的)和几行(数字是动态的)。我需要把它们放在html模板中。有什么方法可以在代码中组合模板吗?我更喜欢使用模板,而不是在代码中构建表。

我已经检查了一个教程https://github.com/gin-gonic/gin,但是没有涵盖它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-14 14:06:25

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

代码语言:javascript
复制
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/的好地方

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37813067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档