如何将Go的HTML模板嵌入代码中?

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

How to embed Go HTML templates into code?

问题

我有一组模板文件,例如base.htmllogin.htmlprofile.htmlheader.html等,它们被组织在文件夹中。

在开发过程中,将它们作为单独的文件是可以的,但是当我部署应用程序时,我希望将它们全部嵌入为字符串,或者解析和编译为模板,以便像往常一样从代码中使用。

我应该如何将这些模板制作为Go代码?这样我就不需要在生产环境中有一个templates文件夹,而是将所有内容都放在单个可执行文件中。

英文:

I have a set of templates as files, like base.html, login.html, profile.html, header.html and so on. They are structured in folders.

It's fine to have them as separate files during development but when I deploy the app, I'd like to have them all embedded as strings or parsed and compiled templates ready to use from the code as usual.

How should I better make these templates as Go code? So that I don't have to have a templates folder in production, but everything in the single executable file?

答案1

得分: 11

在Go 1.16中,将会有官方的"embed"包,如果你在2021年2月之后阅读这篇文章,以下内容将成为可能:

//go:embed "mytemplate.tmpl"
var myTemplate string

这段代码在编译时将mytemplate.html嵌入,并作为一个字符串(或者作为[]byte或者作为一个文件系统,如果你愿意)可用。不需要第三方工具或库。

英文:

With Go 1.16 there would be official "embed" package and the following would be possible (is possible if you read this after February 2021):

//go:embed "mytemplate.tmpl"
var myTemplate string

This code embeds mytemplate.html at compile time and it becomes available as a string (or as []byte or as a FileSystem, if you wish). No 3rd-party tools or libraries needed.

答案2

得分: 1

最简单的解决方案是在Go源代码中的字符串字面量中嵌入模板。

有一个可以帮助的工具,参见go-bindata

我在之前的一些项目中使用了go generate来进行这种类型的操作,参见关于go generate命令的博文进行介绍。

英文:

The most simple solution is to embed templates in string literal inside Go source code.

There is a tool that can help, see go-bindata.

I used go generate in some of previous projects for this type of operation, see blog post on go generate command for introduction.

1: https://github.com/jteeuwen/go-bindata "go-bindata"
2: https://blog.golang.org/generate%20go-generate

答案3

得分: 1

截至Go 1.16版本,引入了//go:embed注释指令。这使得你可以直接将文件嵌入到二进制文件中。

这是go:embed注释指令的设计草案链接

这是关于go embed的Github问题链接,其中包含一些更新

英文:

As of the Go 1.16 release, there is the //go:embed comment directive.
This allows you to directly embed files in your binary.

Link for draft design of the go:embed comment directive

Link for the Github issue for go embed with some updates

答案4

得分: 0

除了已经提到的go-bindata之外,还有go-bindata-assetfs可以用来从Web服务器上提供静态文件。它适用于JavaScript、CSS等文件。

英文:

In addition to go-bindata which was already mentioned, there is go-bindata-assetfs which you can use to serve static files from a webserver. It's good for Javascript, CSS, etc.

huangapple
  • 本文由 发表于 2017年1月18日 23:59:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/41723876.html
匿名

发表评论

匿名网友

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

确定