Go Template.ParseFiles and filepath.Join

huangapple go评论88阅读模式
英文:

Go Template.ParseFiles and filepath.Join

问题

我正在尝试从目录中加载一个HTML文件,但是出现了错误"打开模板:没有这个文件或目录"。

我的目录结构如下:

/Users/{username}/go/src/app
main.go

/Users/{username}/go/src/app/templates
mytemplate.html

错误出现在下面这行代码:

template.Must(template.ParseFiles(filepath.Join("templates", "mytemplate.html")))

我是Go语言的新手,只是试着熟悉一下语法。

编辑1:

我正在使用"go build"命令构建项目,并在上面显示的"app"目录中执行它。

$GOROOT = /usr/local/go
$GOPATH = /Users/{username}/go

我还更新了目录结构以整合$GOPATH。

英文:

I am trying to load an html file from a directory and I am getting the error "open templates: no such file or directory"

My directory structure is below

/Users/{username}/go/src/app
main.go

/Users/{username}/go/src/app/templates
mytemplate.html

The error is coming from the line below

template.Must(template.ParseFiles(filepath.Join("templates", "mytemplate.html")))

I am new to go and just trying to get a feel for the syntax.

EDIT 1

I am building the project using the "go build" command and executing it out of the "app" directory shown above.

$GOROOT = /usr/local/go
$GOPATH = /Users/{username}/go

I also updated the directory structure to integrate the $GOPATH

答案1

得分: 1

请检查你的程序在运行时的工作目录:

dir, _ := os.Getwd()
fmt.Println(dir)

然后你可以使用这个目录来获取模板的正确路径:

template.Must(template.ParseFiles(filepath.Join(dir, "templates", "mytemplate.html")))

对于生产环境,你可以从配置文件或环境中获取dir的值。

参考:https://golang.org/pkg/os/#Getwd

编辑:在运行程序时,请确保你在终端中使用cd命令进入正确的目录。

英文:

Check the working directory that your program has at runtime with

dir, _ := os.Getwd()
fmt.Println(dir)

Then you can use that to get the right path for the templates

template.Must(template.ParseFiles(filepath.Join(dir, "templates", "mytemplate.html")))

For production use you could get the val of dir fro a config file or the environment,

ref : https://golang.org/pkg/os/#Getwd

EDIT: When you run the program make sure you are in the correct directory using cd in your terminal

答案2

得分: -1

请尝试这样做:

template.Must(template.New("mytemplate.html").ParseFiles("templates/mytemplate.html"))
英文:

Try this,

template.Must(template.New("mytemplate.html").ParseFiles("templates/mytemplate.html"))

huangapple
  • 本文由 发表于 2015年9月14日 08:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/32556020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定