官方地址:https://golang.org/pkg/html/template/
翻译: https://colobu.com/2019/11/05/Golang-Templates-Cheatsheet/#if/else_%E8%AF%AD%E5%8F%A5
1. 设置静态文件路径
package mainimport ("net/http""github.com/gin-gonic/gin")func main() {// 创建一个默认的路由引擎r := gin.Default()// 配置模板r.LoadHTMLGlob("templates/**/*")//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")// 配置静态文件夹路径 第一个参数是api,第二个是文件夹路径r.StaticFS("/static", http.Dir("./static"))// GET:请求方式;/hello:请求的路径// 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数r.GET("/posts/index", func(c *gin.Context) {// c.JSON:返回JSON格式的数据c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{"title": "posts/index",})})r.GET("gets/login", func(c *gin.Context) {c.HTML(http.StatusOK, "posts/login.tmpl", gin.H{"title": "gets/login",})})// 启动HTTP服务,默认在0.0.0.0:8080启动服务r.Run()}
2. index.html内容
<html><h1>{{ .title }}</h1></html>
3. templates/posts/index.tmpl
{{ define "posts/index.tmpl" }}<html><h1>{{ .title }}</h1><p>Using posts/index.tmpl</p></html>{{ end }}
4. templates/users/index.tmpl
{{ define "users/index.tmpl" }}<html><h1>{{ .title }}</h1><p>Using users/index.tmpl</p></html>{{ end }}
