diff --git a/common/maps/scratch.go b/common/maps/scratch.go index ccd03ef3..26ffef7d 100644 --- a/common/maps/scratch.go +++ b/common/maps/scratch.go @@ -129,6 +129,17 @@ func (c *Scratch) SetInMap(key string, mapKey string, value interface{}) string return "" } +// DeleteInMap deletes a value to a map with the given key in the Node context. +func (c *Scratch) DeleteInMap(key string, mapKey string) string { + c.mu.Lock() + _, found := c.values[key] + if found { + delete(c.values[key].(map[string]interface{}), mapKey) + } + c.mu.Unlock() + return "" +} + // GetSortedMapValues returns a sorted map previously filled with SetInMap. func (c *Scratch) GetSortedMapValues(key string) interface{} { c.mu.RLock() diff --git a/common/maps/scratch_test.go b/common/maps/scratch_test.go index d893ccb0..96b35257 100644 --- a/common/maps/scratch_test.go +++ b/common/maps/scratch_test.go @@ -188,6 +188,20 @@ func TestScratchSetInMap(t *testing.T) { c.Assert(scratch.GetSortedMapValues("key"), qt.DeepEquals, []interface{}{0: "Abc (updated)", 1: "Def", 2: "Lux", 3: "Zyx"}) } +func TestScratchDeleteInMap(t *testing.T) { + t.Parallel() + c := qt.New(t) + + scratch := NewScratch() + scratch.SetInMap("key", "lux", "Lux") + scratch.SetInMap("key", "abc", "Abc") + scratch.SetInMap("key", "zyx", "Zyx") + scratch.DeleteInMap("key", "abc") + scratch.SetInMap("key", "def", "Def") + scratch.DeleteInMap("key", "lmn") // Do nothing + c.Assert(scratch.GetSortedMapValues("key"), qt.DeepEquals, []interface{}{0: "Def", 1: "Lux", 2: "Zyx"}) +} + func TestScratchGetSortedMapValues(t *testing.T) { t.Parallel() scratch := NewScratch() diff --git a/docs/content/en/functions/scratch.md b/docs/content/en/functions/scratch.md index 10623b2c..f42b0ad5 100644 --- a/docs/content/en/functions/scratch.md +++ b/docs/content/en/functions/scratch.md @@ -97,6 +97,18 @@ Takes a `key`, `mapKey` and `value` and add a map of `mapKey` and `value` to the {{ .Scratch.Get "greetings" }} > map[french:Bonjour english:Hello] ``` +#### .DeleteInMap +Takes a `key` and `mapKey` and removes the map of `mapKey` from the given `key`. + +```go-html-template +{{ .Scratch.SetInMap "greetings" "english" "Hello" }} +{{ .Scratch.SetInMap "greetings" "french" "Bonjour" }} +---- +{{ .Scratch.DeleteInMap "greetings" "english" }} +---- +{{ .Scratch.Get "greetings" }} > map[french:Bonjour] +``` + #### .GetSortedMapValues Returns array of values from `key` sorted by `mapKey`