Run binary from anywhere with templates


#1

I followed the example on the forums about using the echo template render. It works perfectly when I run my binary from the projects working directory however if I run it outside my projects directory I get the error:

panic: html/template: pattern matches no files: public/*.html

I want to be able to package up my templates in my binary, so I can run it from anywhere. I have found this but haven’t managed to get it to work with the echo template render.

Has anyone had any success doing this with echo?


#2

Yes, I’ve used go-bindata with echo (as well as in other scenarios) and it just works. You need two things: load the data into your code when building it and then just use it :slight_smile: Trying to load them from disk is wasteful, why do that since you already have that data in code?

Here’s what I used (my templates were located under a ./templates/… folder):

//go:generate go-bindata -o templates.go templates/

package main

import (
	"html/template"
	"strings"
)

var tpl = template.New("base")

func init() {
	for _, name := range AssetNames() {
		if strings.HasPrefix(name, "templates/") {
			asset, err := Asset(name)
			if err != nil {
				panic(err)
			}

			if _, err := tpl.Parse(string(asset)); err != nil {
				panic(err)
			}
		}
	}
}

Hope it helps!

Cheers!
Alex