How can I add, set and delete keys in a dictionary?

Hi!

I’m learning Hugo templates at the moment and trying to learn how to do some basic things with dictionaries.

In particular:

  • add a new item to a dictionary
  • change an existing item in a dictionary
  • delete an item from a dictionary

In JavaScript I could do something like:

const dictionary = { a:1, b:2, c:3 }  // initialize a dict
// { a: 1, b: 2, c: 3}

dictionary.d = 4                      // add a new item
// { a: 1, b: 2, c: 3, d: 4 }

dictionary.c = 5                      // change an existing item
// { a: 1, b: 2, c: 5, d: 4 }

delete dictionary.a                   // delete an item
// { b: 2, c: 5, d: 4 }

…but I’m not sure what the equivalent is in a Hugo template. It seems I can do some of these things using merge but it’s not quite the same - for example, if the item being set is itself a dictionary, then its keys are merged with the target item’s keys, rather than the target item just being replaced.

Sorry if the answer is really obvious!

Will

1 Like

As far as I know, merge is the only tool in the bag. There’s a related GitHub issue, closed due to lack of activity:

1 Like

Thank you @jmooring ! Following the link you posted, it looks like .Scratch does what I need:

{{ $scratch := newScratch }}

{{ $scratch.Set "a" 1 }}
{{ $scratch.Set "b" 2 }}
{{ $scratch.Set "c" 3 }}

{{ $scratch.Set "d" 4 }}

{{ $scratch.Set "c" 5 }}

{{ $scratch.Delete "a" }}
2 Likes