Skip to content

Commit

Permalink
✨ More robust templates
Browse files Browse the repository at this point in the history
  • Loading branch information
wesen committed Jan 27, 2025
1 parent 3f08927 commit 7fb4a0d
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions cmd/tools/test-html-selector/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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)
}
Expand Down Expand Up @@ -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",
Expand Down

0 comments on commit 7fb4a0d

Please sign in to comment.