Templater
Templater is a code generation tool for Go projects that creates files based on templates and configuration structures. It simplifies the process of generating repetitive code patterns.
Overview
Templater works by:
- Reading Go source files that contain template configurations
- Processing template files with the provided configuration values
- Generating new Go files based on these templates
Installation
go install github.com/zerops-dev/templater/cmd/...@latest
Usage
Basic Usage
- Create a template structure
- Create a template file that contains Go code with template placeholders.
- In your source file, add a
go:generate directive and a configuration variable.
- Run
go generate to create the output files.
Example
Let's say you want to generate record types with different names. First, create a configuration structure:
package templates
type MyTemplate struct {
Name string
Extended bool
}
These fields can then be referenced in your templates using the dot notation ({{.Name}}, {{.Extended}}). Templater uses Go's built-in text/template syntax.
Then create a template with placeholders for your dynamic values.
package finalPackageNameWillBeReplaced
type Records{{.Name}} struct {
}
func (r Records{{.Name}}) Name() string {
return "{{.Name}}"
}
{{if .Extended }}
func(r Records{{.Name}}) ExtendedName() string {
return "Exteded{{.Name}}"
}
{{end}}
Everywhere you want to use template, import template structure and add generate macro.
package myProject
//go:generate gomodrun templater
var _ = templates.MyTemplate{Name: "mx", Extended: false}
When you run go generate, templater will process the template with your configuration values and generate a new file:
//go:build !templater
// +build !templater
// Code generated by "templater"; DO NOT EDIT.
// source: myTemplate.go
package myProject
type Recordsmx struct {
Value int
}
func (r Recordsmx) Name() string {
return "mx"
}
Generated files include build tags to ensure they aren't processed by the templater itself:
//go:build !templater
// +build !templater
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.