user776942
user776942

Reputation:

How can I access the templates outside of the package?

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?

Upvotes: 2

Views: 523

Answers (2)

Dean Elbaz
Dean Elbaz

Reputation: 2450

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

Upvotes: 1

Momer
Momer

Reputation: 3237

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

Upvotes: 0

Related Questions