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

Bil*_*ill 12 go

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

App
  - Template
    - foo.go
    - foo.tmpl
  - Model
    - bar.go
  - Another
    - Directory
      - baz.go
Run Code Online (Sandbox Code Playgroud)

该文件foo.go用于ParseFiles读取模板文件init.

import "text/template"

var qTemplate *template.Template

func init() {
  qTemplate = template.Must(template.New("temp").ParseFiles("foo.tmpl"))
}

...
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我已经尝试将模板名称指定为相对目录("./foo.tmpl"),一个完整目录("〜/ go/src/github.com/App/Template/foo.tmpl"),一个App亲戚目录("/App/Template/foo.tmpl")和其他人,但似乎没有任何东西适用于这两种情况.单元测试失败bar.gobaz.go(或两者).

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

Lar*_*tle 13

有用的提示:

使用os.Getwd()filepath.Join()查找相对文件路径的绝对路径.

// File: showPath.go
package main
import (
        "fmt"
        "path/filepath"
        "os"
)
func main(){
        cwd, _ := os.Getwd()
        fmt.Println( filepath.Join( cwd, "./template/index.gtpl" ) )
}
Run Code Online (Sandbox Code Playgroud)

首先,我建议该template文件夹仅包含演示文稿的模板,而不是go文件.

接下来,为了简化生活,只运行根项目目录中的文件.这将有助于使嵌套在子目录中的整个文件中的文件路径保持一致.相对文件路径从当前工作目录的位置开始,该目录是调用程序的位置.

显示当前工作目录中的更改的示例

user@user:~/go/src/test$ go run showPath.go
/home/user/go/src/test/template/index.gtpl
user@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
Run Code Online (Sandbox Code Playgroud)

对于测试文件,您可以通过提供文件名来运行单个测试文件.

go test foo/foo_test.go
Run Code Online (Sandbox Code Playgroud)

最后,使用基本路径和path/filepath包来形成文件路径.

例:

var (
  basePath = "./public"
  templatePath = filepath.Join(basePath, "template")
  indexFile = filepath.Join(templatePath, "index.gtpl")
) 
Run Code Online (Sandbox Code Playgroud)