如何在包外访问模板?

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

How can I access the templates outside of the package?

问题

我已经根据这个结构设置了一个简单的网站。我运行main.go一切正常。我想在另一个包中使用这个web应用,比如"github.com/my/package"。我将"main.go"复制到"github.com/my/package"目录中并运行,但是出现以下错误:

"panic: open templates/user/view.html: no such file or directory"

这个文件中,修改模板文件的路径的推荐方法是什么,以便我可以访问这些模板?我可以想到两种解决方案:

  1. 在view.go中硬编码绝对路径到模板文件。
  2. 在view.go中设置一个全局变量,然后找出模板文件相对于新的main.go文件的路径,并将该路径设置为该变量的值。

第一种方法显然会在其他人尝试使用该包时出错。第二种方法有点复杂,因为你需要找到main的路径,然后逐步找出模板的位置...似乎非常复杂。

有更好的方法吗?

英文:

I have setup a simple website based off of this structure. I run main.go and everything works fine. I'd like to be able to use this webapp in another package, say "github.com/my/package". I copied "main.go" to the "github.com/my/package" directory and run it but then get:

"panic: open templates/user/view.html: no such file or directory"

What is the recommended way to modify the path to the template file in this file, for instance, so that I can access the templates? I can think of two solutions:

  1. Hardcode an absolute path in view.go to the template file.
  2. Have a global variable in view.go then figure out where the template files are in relation to the new main.go file & set the variable to that path.

The first will obviously break if someone else were to try to use the package. The second option is a bit convoluted b/c you need to find the path to main then work your way through & figure out where the templates are...seems very convoluted.

Is there a better way?

答案1

得分: 1

你可以查看go-bindata。它可以将外部文件(如模板)作为二进制文件的一部分。尽管这不是一个很好的解决方案,如果你想要在不重新编译的情况下更改模板的话。

英文:

you could look at go-bindata. It makes external files, like templates, as part of the binary. Although it's not a great solution if you want to be able to change the templates without recompiling

答案2

得分: 0

如果有功能旨在作为包/在其他地方重复使用,则惯用的做法是将该功能移入一个包中,通常放在pkg目录下。

一个必须提到的例子是camlistore,可以在https://github.com/camlistore/camlistore/tree/master/pkg找到。

另一个学习如何做到这一点的资源是《12个Go语言最佳实践》演讲(https://talks.golang.org/2013/bestpractices.slide#18)。

英文:

If there is functionality meant to be used as a package/reused elsewhere, then the idiomatic way to do this is to move that functionality into a package - typically in the pkg directory.

Obligatory camlistore example is at https://github.com/camlistore/camlistore/tree/master/pkg

Another resource for how to do this is the '12 golang best practices' talk

huangapple
  • 本文由 发表于 2014年12月11日 13:42:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/27416133.html
匿名

发表评论

匿名网友

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

确定