Go:为 template.ParseFiles 指定模板文件名

我当前的目录结构如下所示:


App

  - Template

    - foo.go

    - foo.tmpl

  - Model

    - bar.go

  - Another

    - Directory

      - baz.go

该文件foo.go用于ParseFiles在init.


import "text/template"


var qTemplate *template.Template


func init() {

  qTemplate = template.Must(template.New("temp").ParseFiles("foo.tmpl"))

}


...

foo.go按预期工作的单元测试。不过,我现在想为运行单元测试bar.go和baz.go这两个进口foo.go和我得到试图打开一个恐慌foo.tmpl。


/App/Model$ go test    

panic: open foo.tmpl: no such file or directory


/App/Another/Directory$ go test    

panic: open foo.tmpl: no such file or directory

我尝试将模板名称指定为相对目录(“./foo.tmpl”)、完整目录(“~/go/src/github.com/App/Template/foo.tmpl”)、应用程序相关目录(“/App/Template/foo.tmpl”)等,但似乎对这两种情况都不起作用。单元测试失败之一bar.go或baz.go(或两者)。


我的模板文件应该放在哪里,我应该如何调用,ParseFiles以便无论我go test从哪个目录调用它,它总能找到模板文件?


婷婷同学_
浏览 365回答 1
1回答

肥皂起泡泡

有用的提示:使用os.Getwd()和filepath.Join()查找相对文件路径的绝对路径。例子// File: showPath.gopackage mainimport (        "fmt"        "path/filepath"        "os")func main(){        cwd, _ := os.Getwd()        fmt.Println( filepath.Join( cwd, "./template/index.gtpl" ) )}首先,我建议该template文件夹仅包含演示模板,而不包含 go 文件。接下来,为了让生活更轻松,只运行项目根目录中的文件。这将有助于使文件路径在嵌套在子目录中的 go 文件中保持一致。相对文件路径从当前工作目录开始,这是调用程序的位置。显示当前工作目录更改的示例user@user:~/go/src/test$ go run showPath.go/home/user/go/src/test/template/index.gtpluser@user:~/go/src/test$ cd newFolder/user@user:~/go/src/test/newFolder$ go run ../showPath.go /home/user/go/src/test/newFolder/template/index.gtpl至于测试文件,您可以通过提供文件名来运行单个测试文件。go test foo/foo_test.go最后,使用基本路径和path/filepath包来形成文件路径。例子:var (  basePath = "./public"  templatePath = filepath.Join(basePath, "template")  indexFile = filepath.Join(templatePath, "index.gtpl")) 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go