3

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?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • 2
    Possible duplicate of [What's the best way to bundle static resources in a Go program?](http://stackoverflow.com/questions/13904441/whats-the-best-way-to-bundle-static-resources-in-a-go-program/28071360#28071360) – icza Jan 18 '17 at 16:09
  • 3
    Possible duplicate of http://stackoverflow.com/questions/17796043/embedding-text-file-into-compiled-executable – Matej Baćo Jan 18 '17 at 16:13
  • 1
    Possible duplicate of [What's the best way to bundle static resources in a Go program?](http://stackoverflow.com/questions/13904441/whats-the-best-way-to-bundle-static-resources-in-a-go-program) – hlscalon Jan 18 '17 at 17:14

4 Answers4

11

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.

zserge
  • 2,212
  • 2
  • 31
  • 40
1

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.

Matej Baćo
  • 1,312
  • 2
  • 10
  • 12
1

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

Cameron
  • 2,903
  • 1
  • 30
  • 31
0

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.

Josh Lubawy
  • 386
  • 1
  • 6