Documentation
¶
Index ¶
Examples ¶
Constants ¶
const ( // DefaultLeftDelim is the default left delimiter for templates DefaultLeftDelim = "{{" // DefaultRightDelim is the default right delimiter for templates DefaultRightDelim = "}}" )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ExecuteResult ¶
type ExecuteResult struct {
// Output is the rendered template content
Output string
// TemplateName is the name/identifier of the template
TemplateName string
// ReplacementsMade is the number of replacements that were applied
ReplacementsMade int
}
ExecuteResult contains the result of template execution
func Execute ¶
func Execute(ctx context.Context, opts TemplateOptions) (*ExecuteResult, error)
Execute is a convenience function that creates a service and executes a template For one-off template execution without custom default functions
Example ¶
ExampleExecute demonstrates basic template execution
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
result, err := gotmpl.Execute(ctx, gotmpl.TemplateOptions{
Name: "greeting.tmpl",
Content: "Hello, {{.Name}}! You are {{.Age}} years old.",
Data: map[string]any{
"Name": "Alice",
"Age": 30,
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Hello, Alice! You are 30 years old.
type GoTemplatingContent ¶
type GoTemplatingContent string
type MissingKeyOption ¶
type MissingKeyOption string
MissingKeyOption defines the behavior when a map key is missing during template execution
const ( // MissingKeyDefault continues execution and prints "<no value>" for missing keys // This is the default behavior MissingKeyDefault MissingKeyOption = "default" // MissingKeyZero returns the zero value for the map type's element MissingKeyZero MissingKeyOption = "zero" // MissingKeyError stops execution immediately with an error MissingKeyError MissingKeyOption = "error" )
type Replacement ¶
type Replacement struct {
// Find is the string to search for in the template content
Find string
// Replace is the temporary replacement value
// If empty, a UUID will be generated automatically
Replace string
}
Replacement defines a string replacement to perform before/after templating
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides template execution capabilities
func NewService ¶
NewService creates a new template service with optional default functions
func (*Service) Execute ¶
func (s *Service) Execute(ctx context.Context, opts TemplateOptions) (*ExecuteResult, error)
Execute renders a template with the provided options
Example (Complex) ¶
ExampleService_Execute_complex demonstrates combining multiple features
package main
import (
"context"
"fmt"
"log"
"text/template"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
// Create service with helper functions
svc := gotmpl.NewService(template.FuncMap{
"default": func(defaultVal, val string) string {
if val == "" {
return defaultVal
}
return val
},
})
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "report.tmpl",
Content: "User: [[.Name]], Status: [[default \"inactive\" .Status]], Code: LITERAL_CODE",
LeftDelim: "[[",
RightDelim: "]]",
Data: map[string]any{
"Name": "David",
"Status": "",
},
Replacements: []gotmpl.Replacement{
{Find: "LITERAL_CODE", Replace: "TEMP_12345"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: User: David, Status: inactive, Code: LITERAL_CODE
Example (CustomDelimiters) ¶
ExampleService_Execute_customDelimiters shows using custom delimiters
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "jinja-style.tmpl",
Content: "Welcome, [[.User]]!",
LeftDelim: "[[",
RightDelim: "]]",
Data: map[string]any{
"User": "Bob",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Welcome, Bob!
Example (CustomFunctions) ¶
ExampleService_Execute_customFunctions demonstrates using custom template functions
package main
import (
"context"
"fmt"
"log"
"strings"
"text/template"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
// Create service with default functions
svc := gotmpl.NewService(template.FuncMap{
"upper": strings.ToUpper,
"lower": strings.ToLower,
})
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "formatted.tmpl",
Content: "{{upper .FirstName}} {{lower .LastName}}",
Data: map[string]any{
"FirstName": "john",
"LastName": "DOE",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: JOHN doe
Example (LoopAndConditionals) ¶
ExampleService_Execute_loopAndConditionals shows template control structures
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
content := `{{if .Title}}Title: {{.Title}}
{{end}}Items:{{range .Items}}
- {{.}}{{end}}`
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "list.tmpl",
Content: content,
Data: map[string]any{
"Title": "Shopping List",
"Items": []string{"Apples", "Bananas", "Oranges"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Title: Shopping List Items: - Apples - Bananas - Oranges
Example (MissingKeyHandling) ¶
ExampleService_Execute_missingKeyHandling demonstrates handling missing keys
package main
import (
"context"
"fmt"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
// Default behavior: prints "<no value>"
result1, _ := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "default.tmpl",
Content: "Status: {{.Status}}",
Data: map[string]any{}, // Status key missing
MissingKey: gotmpl.MissingKeyDefault,
})
fmt.Println(result1.Output)
// Zero behavior: returns zero value (empty string for string type)
result2, _ := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "zero.tmpl",
Content: "Count: {{.Count}}",
Data: map[string]any{}, // Count key missing
MissingKey: gotmpl.MissingKeyZero,
})
fmt.Println(result2.Output)
}
Output: Status: <no value> Count: <no value>
Example (Replacements) ¶
ExampleService_Execute_replacements shows protecting literal strings from template processing
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
// Template contains both template syntax and literal template syntax
content := `Name: {{.Name}}
Literal template syntax: {{KEEP_THIS_LITERAL}}`
result, err := svc.Execute(ctx, gotmpl.TemplateOptions{
Name: "mixed.tmpl",
Content: content,
Data: map[string]any{
"Name": "Charlie",
},
Replacements: []gotmpl.Replacement{
{Find: "{{KEEP_THIS_LITERAL}}"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Output)
}
Output: Name: Charlie Literal template syntax: {{KEEP_THIS_LITERAL}}
func (*Service) GetReferences ¶
func (s *Service) GetReferences(ctx context.Context, opts TemplateOptions) ([]TemplateReference, error)
GetReferences extracts all references to Data from a Go template This method parses the template and extracts variable references (e.g., .User, .Items) It excludes function calls and Go template control variables (like $var)
Example ¶
ExampleService_GetReferences demonstrates extracting references using the Service
package main
import (
"context"
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
"github.com/oakwood-commons/scafctl/pkg/logger"
)
func main() {
ctx := logger.WithLogger(context.Background(), logger.Get(0))
svc := gotmpl.NewService(nil)
refs, err := svc.GetReferences(ctx, gotmpl.TemplateOptions{
Name: "config.tmpl",
Content: "[[.App.Name]] version [[.App.Version]]",
LeftDelim: "[[",
RightDelim: "]]",
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Template references:")
for _, ref := range refs {
fmt.Printf(" %s\n", ref.Path)
}
}
Output: Template references: .App.Name .App.Version
type TemplateOptions ¶
type TemplateOptions struct {
// Content is the template content as a string
Content string
// Name is the reference name/identifier for the template (e.g., file path)
// Used in logging and error messages
Name string
// Data is the data source passed to the template during execution
Data any
// LeftDelim sets the left action delimiter (default: "{{")
LeftDelim string
// RightDelim sets the right action delimiter (default: "}}")
RightDelim string
// Replacements is a map of strings to replace before template execution
// The key is replaced with a UUID placeholder, then restored after execution
// This helps avoid template parsing errors for content that should be literal
Replacements []Replacement
// Funcs is a map of custom template functions to make available
// These are added to the template's function map
Funcs template.FuncMap
// MissingKey controls the behavior when a map key is missing
// Default: MissingKeyDefault (prints "<no value>")
// Options: MissingKeyDefault, MissingKeyZero, MissingKeyError
MissingKey MissingKeyOption
// DisableBuiltinFuncs disables the built-in template functions
// By default, basic functions like "html", "js", etc. are available
DisableBuiltinFuncs bool
}
TemplateOptions contains configuration for template execution
type TemplateReference ¶
type TemplateReference struct {
// Path is the dot-notation path to the data (e.g., ".User.Name", ".Items")
Path string
// Position is the line:column position in the template (if available)
Position string
}
TemplateReference represents a reference to data in a template
func GetGoTemplateReferences ¶
func GetGoTemplateReferences(templateContent, leftDelim, rightDelim string) ([]TemplateReference, error)
GetGoTemplateReferences is a convenience function that creates a service and extracts references For one-off reference extraction without needing to create a service
Example ¶
ExampleGetGoTemplateReferences demonstrates extracting data references from templates using the convenience function
package main
import (
"fmt"
"log"
"github.com/oakwood-commons/scafctl/pkg/gotmpl"
)
func main() {
template := `
{{if .User.IsAdmin}}
Welcome, {{.User.Name}}!
{{range .User.Permissions}}
- {{.}}
{{end}}
{{end}}
`
refs, err := gotmpl.GetGoTemplateReferences(template, "", "")
if err != nil {
log.Fatal(err)
}
fmt.Println("Found references:")
for _, ref := range refs {
fmt.Printf(" %s\n", ref.Path)
}
}
Output: Found references: .User.IsAdmin .User.Name .User.Permissions