欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > golang gin template模板渲染

golang gin template模板渲染

2024/10/25 13:23:02 来源:https://blog.csdn.net/wx479/article/details/141606186  浏览:    关键词:golang gin template模板渲染

1、根据值控制html元素显示隐藏

main.go

package main
import ("html/template""net/http""github.com/gin-gonic/gin"
)
func main() {r := gin.Default()r.SetFuncMap(template.FuncMap{"greaterThan": func(a, b int) bool {return a > b},})r.LoadHTMLGlob("templates/*")r.GET("/", func(c *gin.Context) {value := 10 // 示例值c.HTML(http.StatusOK, "index.html", gin.H{"Value": value,})})r.Run()
}

index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Example</title>
</head>
<body>{{ if greaterThan .Value 5 }}<div>Value is greater than 5</div>{{ end }}
</body>
</html>

在 Go 的 Gin 框架中,可以使用条件语句在 HTML 模板中控制元素的渲染。假设你有一个变量 `value`,你想根据它的值来决定是否渲染某个 HTML 元素,可以这样做:

这段代码会在 `value` 大于 5 时显示指定的 `<div>` 元素。否则,该元素将不会被渲染。

显示结果

2、循环遍历列表生成html元素

main.go

package mainimport ("github.com/gin-gonic/gin""net/http"
)type ListArr struct {Name stringAge  int
}func main() {r := gin.Default()l := [3]ListArr{{Name: "bob", Age: 20},{Name: "jack", Age: 30},{Name: "alice", Age: 32},}r.LoadHTMLGlob("templates/*")r.GET("/", func(c *gin.Context) {c.HTML(http.StatusOK, "index.html", gin.H{"List": l,})})r.Run(":9999")
}

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Example</title>
</head>
<body>{{range .List}}<p>my name is {{.Name}} my age is {{.Age}}</p>{{end}}
</body>
</html>

运行效果

3、一和二结合使用

main.go

package mainimport ("github.com/gin-gonic/gin""html/template""net/http"
)type ListArr struct {Name stringAge  int
}func main() {r := gin.Default()r.SetFuncMap(template.FuncMap{"greaterThan": func(a, b int) bool {return a > b},})l := [3]ListArr{{Name: "bob", Age: 20},{Name: "jack", Age: 30},{Name: "alice", Age: 32},}r.LoadHTMLGlob("templates/*")r.GET("/", func(c *gin.Context) {c.HTML(http.StatusOK, "index.html", gin.H{"List": l,})})r.Run(":9999")
}

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Example</title>
</head>
<body>{{range .List}}{{ if greaterThan .Age 25 }}<p>my name is {{.Name}} my age is {{.Age}} 年龄超过了25岁</p>{{ else }}<p>my name is {{.Name}} my age is {{.Age}} 年龄没有25岁</p>{{ end }}{{end}}
</body>
</html>

运行效果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com