Skip to content

keys function does not work with map[string]struct #455

@prune998

Description

@prune998

I want to get the string keys of a dict which is a map[string]string (or anything different from map[string]interface.

Ex script:

package main

import (
	"html/template"
	"os"

	"github.com/Masterminds/sprig/v3"
)

func main() {
	// Define your data, a map[string]interface{} in this case
	data := map[string]interface{}{
		"MyMap": map[string]string{
			"key1": "value1",
			"key2": "value2",
			"key3": "value3",
		},
	}

	// Create a new template and add Sprig functions
	tmpl, err := template.New("example").Funcs(sprig.FuncMap()).Parse(`
Sprig Keys Example
Keys of MyMap:
  {{ range $key := .MyMap | keys }}
    {{ $key }}
  {{ end }}
	`)
	if err != nil {
		panic(err)
	}

	// Execute the template with the data
	err = tmpl.Execute(os.Stdout, data)
	if err != nil {
		panic(err)
	}
}

This gives an error:

panic: template: example:4:28: executing "example" at <keys>: wrong type for value; expected map[string]interface {}; got map[string]string

I consider that a bug... keys shouldn't care of the values, only the keys... An I missing something ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions