Build a map from a string which is split twice

I see the mergeMap function and that is useful if I have keys and values under a tree, but what if I have a single key which has map data in it.

e.g. in the foo key I have a value like
bar => baz ; bad => good ; things => stuff

I’d like to write a consul-template which uses this data.

I’m currently struggling with doing it using scratch and now I think there should be a better way.

{{ range (key "foo" | split ";") -}}
{{- $entry := .| split "=>" -}}
{{if gt (len $entry) 1 }}
{{- scratch.Set (index $entry 0|trimSpace) (index $entry 1|trimSpace) }}
{{ index $entry 0|trimSpace }}:{{ index $entry 1|trimSpace }}
{{end}}
{{end}}

Is there a helper function, splitToMap which takes two args and returns a map? or an equivalent way to do this?

If not, would a PR be accepted adding this functionality?

Hey @jrwren! Thanks for the question.

My initial thought is maybe something using the sprig.regexFindAll()?

PRs are always welcome, though I’m not 100% on splitToMap as a new function. How exactly would it behave? Or did you have another idea for how to simplify this?

Thanks!

Thanks @eikenb I’ll take a deeper look at sprig…

Good lord, why did they name them “dict” functions when this is a Go library. I had been searching for map. This is not obvious to gophers… Dictionaries and Dict Functions | sprig

I think I can range and split and use sprig_dict, but it still seems like a poor solution compared to a splitToMap function.

// splitToMap is a version of strings.Split which splits a second time for each
// item in the slice generated from the first split, building a map
func splitToMap(sep1, sep2, s string) (map[string]string, error) {
	s = strings.TrimSpace(s)
	if s == "" {
		emptyMap := make(map[string]string)
		return emptyMap, nil
	}
	s1 := strings.Split(s, sep1)
	m:=make(map[string]string, len(s1))
	for i := range s1 {
		k,v,f:=strings.Cut(s1[i],sep2)
		if !f {
			continue
		}
		m[k]=v
	}
	return m, nil
}

Thanks for the pointers.

I sent a PR. Take it or leave it: Enable template function splitToMap by jrwren · Pull Request #1664 · hashicorp/consul-template · GitHub