Skip to content

5nord/template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go template helper

If you use go generate to generate files from Go templates, this package is for you.

template.Generate evaluates all .tmpl files in the given directory and writes the output to files with the .tmpl suffix removed.

All files with .go suffix will additionally be formatted with go/format.

Example

$ ls
example_gen.go.tmpl gen.go  main.go
// main.go:
// - uses generated code
// - triggers the generate script.

//go:generate go run gen.go

package main

import "fmt"

func main() {
	fmt.Println(When)
}
// example_gen.go.tmpl:
// - template for `example_gen.go`
// - exports the generated code.

// Code generated by go generate; DO NOT EDIT.
// This file was generated by robots at {{now}}

package main

const When = "{{now}}"
// gen.go
// - generator script
// - runs the Generate function
// - is only run by `go generate` 

//go:build ignore

package main

import (
	"log"
	"time"

	"github.com/5nord/template"
)

func main() {
	if err := template.Generate(".", map[string]any{
		"now": func() string {
			return time.Now().Format(time.DateTime)
		},
	}, nil); err != nil {
		log.Fatal(err)
	}
}

When we run go generate we'll have a new file:

$ go generate
$ ls
example_gen.go  example_gen.go.tmpl gen.go  main.go

$ cat example_gen.go
// Code generated by go generate; DO NOT EDIT.
// This file was generated by robots at 2026-05-07 11:12:35

package main

const When = "2026-05-07 11:12:35"

Notes

I find it good practice to:

  • Commit generated files. This reduces the number of dependencies and makes building your project easier on your users and you can use your version control system to review changes introduced by your generators.
  • Have a header. Tell the user the file is generated!
  • Include the date. It's good to have some kind of version-indicitator. Using the date introduces some noise, but I find the benefits normally outweight the drawbacks.

About

Go template helper

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors