gin框架中模板的加载
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"os"
"path/filepath"
)
func main() {
router := gin.Default()
// 加载指定目录下的所有文件
//router.LoadHTMLGlob("C:/Users/mayanan/Desktop/pro_go/goRPC/gin_start/09_gin返回html/templates/*")
// 为什么我们通过golan运行go的时候并没有生成main.exe
// 注意:相对路径是相对于项目根目录的路径,而不是当对于当前main文件的路径
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fmt.Println(dir)
// 1. 加载指定文件
//router.LoadHTMLFiles("templates/index.tmpl")
// 2. 加载目录下所有文件
//router.LoadHTMLGlob("templates/*")
// 3. 加载多级目录下的相同文件, 注意加载多级目录下的相同文件,需要的模板文件中加入define 和 end标签
router.LoadHTMLGlob("templates/**/*")
// 如果没有在模板文件中定义define,那么我们就可以使用文件名称来找
// 如果不同目录下有相同的文件名,那么就必须在模板文件中是使用define定义来区分相同文件
router.GET("/goods/list", func(context *gin.Context) {
context.HTML(http.StatusOK, "goods/list.tmpl", gin.H{
"title": "慕课网",
})
})
router.GET("/users/list", func(context *gin.Context) {
context.HTML(http.StatusOK, "users/list.tmpl", gin.H{
"title": "慕课网",
})
})
router.GET("/index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "首页",
})
})
router.Run()
}
注意因为使用了模板,当启动go程序的时候从goland的终端启动,不要直接通过goland的右键运行启动
gin/html源码