Go:为template.ParseFiles指定模板文件名
我当前的目录结构如下所示:Go:为template.ParseFiles指定模板文件名,go,Go,我当前的目录结构如下所示: 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 = temp
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
的单元测试按预期工作。但是,我现在正在尝试对导入了foo.go
的bar.go
和baz.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
,它都可以找到模板文件 有用提示:
使用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文件
接下来,为了简化操作,只运行根项目目录中的文件。这将有助于使文件路径在嵌套在子目录中的所有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")
)
你能举一个清晰的例子说明你想做什么吗?我尝试了
模型中的解析文件(“../Template/foo.tmpl”)
,效果很好。但如果我尝试在更深的目录中运行go test
,它将不再起作用。据我所知,go test
始终设置当前工作目录,然后ParseFiles
将其用作查找模板的基本目录,而不是相对于调用ParseFiles
的文件。这是非常脆弱的,所以我想我一定是做错了什么。我已经更新了我的问题,以显示我遇到的问题。