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

时间:2013-09-26 17:51:20

标签: go

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

App
  - Template
    - foo.go
    - foo.tmpl
  - Model
    - bar.go
  - Another
    - Directory
      - baz.go

文件foo.go使用ParseFilesinit期间读取模板文件。

import "text/template"

var qTemplate *template.Template

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

...

foo.go的单元测试按预期工作。但是,我现在正在尝试对导致bar.go的{​​{1}}和baz.go进行单元测试,并且在尝试打开foo.go时会感到恐慌。

foo.tmpl

我已经尝试将模板名称指定为相对目录(“./foo.tmpl”),一个完整目录(“〜/ go / src / github.com / App / Template / foo.tmpl”),一个App相对目录(“/App/Template/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 bar.go(或两者)的单元测试失败。

我的模板文件应该放在哪里以及如何调用baz.go以便始终可以找到模板文件而不管我从哪个目录调用ParseFiles

1 个答案:

答案 0 :(得分:12)

有用的提示:

使用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" ) )
}

首先,我建议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

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

go test foo/foo_test.go

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

示例:

var (
  basePath = "./public"
  templatePath = filepath.Join(basePath, "template")
  indexFile = filepath.Join(templatePath, "index.gtpl")
)