英文:
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"
在这个文件中,修改模板文件的路径的推荐方法是什么,以便我可以访问这些模板?我可以想到两种解决方案:
- 在view.go中硬编码绝对路径到模板文件。
- 在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:
- Hardcode an absolute path in view.go to the template file.
- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论