From 7fb4a0d36e61cb9c97395c0bfefbb6f13bb89a11 Mon Sep 17 00:00:00 2001 From: Manuel Odendahl Date: Sun, 26 Jan 2025 19:03:32 -0500 Subject: [PATCH] :sparkles: More robust templates --- cmd/tools/test-html-selector/main.go | 31 +++++++++++++++++++++------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/cmd/tools/test-html-selector/main.go b/cmd/tools/test-html-selector/main.go index f151964..e229e45 100644 --- a/cmd/tools/test-html-selector/main.go +++ b/cmd/tools/test-html-selector/main.go @@ -344,10 +344,13 @@ func (c *HTMLSelectorCommand) RunIntoWriter( // First try command line template if s.ExtractTemplate != "" { - // Load and execute template - tmpl, err := template.New(s.ExtractTemplate). - Funcs(sprig.TxtFuncMap()). - ParseFiles(s.ExtractTemplate) + // Load template content + content, err := os.ReadFile(s.ExtractTemplate) + if err != nil { + return fmt.Errorf("failed to read template file: %w", err) + } + + tmpl, err := parseTemplate(s.ExtractTemplate, string(content)) if err != nil { return fmt.Errorf("failed to parse template file: %w", err) } @@ -356,10 +359,7 @@ func (c *HTMLSelectorCommand) RunIntoWriter( // Then try config file template if extract mode is on if config != nil && config.Template != "" { - // Parse and execute template from config - tmpl, err := template.New("config"). - Funcs(sprig.TxtFuncMap()). - Parse(config.Template) + tmpl, err := parseTemplate("config", config.Template) if err != nil { return fmt.Errorf("failed to parse template from config: %w", err) } @@ -575,6 +575,21 @@ func executeTemplate(w io.Writer, tmpl *template.Template, sourceResults []*Sour return nil } +// Add this new function near the other helper functions +func parseTemplate(name, content string) (*template.Template, error) { + return template.New(name). + Funcs(sprig.TxtFuncMap()). + Funcs(template.FuncMap{ + "index": func(slice []interface{}, index int) interface{} { + if index < 0 || index >= len(slice) { + return nil + } + return slice[index] + }, + }). + Parse(content) +} + func main() { var rootCmd = &cobra.Command{ Use: "html-selector",