./main.go
文件:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 指定模板路径
router.LoadHTMLGlob("template/*")
router.GET("/index", func(c *gin.Context) {
// HTML(code int, name string, obj interface{}): 状态码, 模板文件, 模板参数
c.HTML(http.StatusOK, "index.html", gin.H{"title": "我是测试"})
})
router.Run()
}
./tempalte/index.html
文件:
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Documenttitle>
head>
<body>
{{.title}}
body>
html>
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 指定模板路径
router.LoadHTMLGlob("template/**/*")
router.GET("/user", func(c *gin.Context) {
// HTML(code int, name string, obj interface{}): 状态码, 模板文件, 模板参数
c.HTML(http.StatusOK, "user.html", gin.H{"title": "我是多级模板测试"})
})
router.Run()
}
tempalte/user/user.html
文件:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
{{.title}}
body>
html>
main.go
文件:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 指定模板路径
router.LoadHTMLGlob("template/**/*")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index/user.html", gin.H{"title": "我是模板继承测试"})
})
router.Run()
}
tempalte/public/header.html
文件:
{{define "public/header"}}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>headertitle>
head>
<body>
<p>我是头部htmlp>
{{end}}
tempalte/public/footer.html
文件:
{{define "public/footer"}}
<p>我是尾部htmlp>
body>
html>
{{ end }}
tempalte/user/user.html
文件:
{{ define "user/index.html" }}
{{template "public/header" .}}
title:{{.title}}
{{template "public/footer" .}}
{{ end }}
main.go
文件:
package main
import (
"github.com/gin-gonic/gin"
"html/template"
"net/http"
)
func main() {
router := gin.Default()
// 布局页面
template.ParseGlob("layout.html")
// 配置模板
router.LoadHTMLGlob("template/**/*")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "user.html", gin.H{"title": "我是模板继承测试"})
})
router.Run()
}
tempalte/public/header.html
文件:
{{define "public/header"}}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>headertitle>
head>
<body>
<p>我是头部htmlp>
{{end}}
tempalte/public/footer.html
文件:
{{define "public/footer"}}
<p>我是尾部htmlp>
body>
html>
{{ end }}
tempalte/public/layout.html
文件:
{{define "public/layout"}}
{{template "public/header" .}}
<div class="container">
{{block "content" . }}{{end}}
div>
{{template "public/footer" .}}
{{ end }}
tempalte/user/user.html
文件:
{{template "public/layout" .}}
{{ define "content" }}
<p>
内容-title:{{.title}}
p>
{{end}}