如何使模板与gin框架一起使用?

ame*_*til 2 go go-templates go-gin

我是golang的新手。为了学习它,我从使用gin框架的简单Web应用程序开始。我已经关注了gin doc和配置的模板文件,但无法使其工作。我遇到错误-

panic: html/template: pattern matches no files: `templates/*`

goroutine 1 [running]:
html/template.Must
  /usr/local/Cellar/go/1.5.2/libexec/src/html/template/template.go:330
github.com/gin-gonic/gin.(*Engine).LoadHTMLGlob
  /Users/ameypatil/deployment/go/src/github.com/gin-gonic/gin/gin.go:126
main.main()
  /Users/ameypatil/deployment/go/src/github.com/ameykpatil/gospike/main.go:17
Run Code Online (Sandbox Code Playgroud)

下面是我的代码-

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    //os.Setenv("GIN_MODE", "release")
    //gin.SetMode(gin.ReleaseMode)

    // Creates a gin router with default middleware:
    // logger and recovery (crash-free) middleware
    router := gin.Default()

    router.LoadHTMLGlob("templates/*")
    //router.LoadHTMLFiles("templates/index.tmpl")

    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "GoSpike",
        })
    })

    // By default it serves on :8080 unless a
    // PORT environment variable was defined.
    router.Run(":4848")
}
Run Code Online (Sandbox Code Playgroud)

我的目录结构是

- gospike
--- templates
------index.tmpl
--- main.go
Run Code Online (Sandbox Code Playgroud)

go install 命令没有给出任何错误

但在实际运行时,会出现上述错误。我搜索了&在gin的github存储库上记录了类似的问题,但现在已关闭。我已经尝试过各种方法,但是我想我缺少明显的东西。我想念什么?

Tom*_*and 5

我猜问题是您正在使用相对文件路径来访问模板。

如果我从该gospike目录编译并运行您的代码,则可以正常工作。但是,如果我gospike从其他任何目录运行,则会收到与您看到的相同的错误。

因此,您需要始终gospike在的父目录中运行templates,或者需要使用绝对路径。您可以对其进行硬编码:

router.LoadHTMLGlob("/go/src/github.com/ameykpatil/gospike/templates/*")
Run Code Online (Sandbox Code Playgroud)

或者你可以做类似的事情

router.LoadHTMLGlob(filepath.Join(os.Getenv("GOPATH"),
    "src/github.com/ameykpatil/gospike/templates/*"))
Run Code Online (Sandbox Code Playgroud)

但是如果您在中设置了多个路径,那将失败GOPATH。更好的长期解决方案可能是设置一个特殊的环境变量,例如TMPL_DIR,然后使用该变量:

router.LoadHTMLGlob(filepath.Join(os.Getenv("TMPL_DIR"), "*"))
Run Code Online (Sandbox Code Playgroud)