Hugo

Add new key value to a map

$ hugo version
Hugo Static Site Generator v0.54.0 darwin/amd64 BuildDate: unknown
$ cat layouts/t/code.html
  ...
  {{- $json := getJSON $path -}}
  {{- if eq $action "edit" -}}
    {{- $json.nestedMap["action"] = "update" -}}
  {{- end -}}
  ...
  <script type="module">
    import App from "/code.js";
    new App({{ $json.nestedMap | jsonify }});
  </script>

$json.nestedMap is map[string]interface {}

but got error parse failed bad character U+005B ‘[’

Thanks for any tips.

Edit: on closer look, we need more info. Your title says you want to add a new entry to a map. But your example says you want to set the value of a map entry. Would you clarify this

You need to post at least the existing map and the new entry for us to know what the issue might be. The error could be more verbose too, it might give you at least a line where the error comes up.

$json.nestedMap["action"] looks weird to me. how about $json.nestedMap.action?

Thanks. I’d like to add value to a key that is not found in the map.

$path is a /data/meta.json file.

$ cat data/meta.json
{
  "nestedMap": {
    "title": "Meta is meta"
  }
}

Thanks.

{{ printf "%#v" $json.nestedMap }}

shows map[string]interface {}{"title":"Meta is meta"}

$ hugo server --debug
...
**ERROR** 2019/07/12 23:38:30 Rebuild failed:
**ERROR** 2019/07/12 23:38:30 **"/path/to/layouts/t/code.html:21:1"** : parse failed: template: t/code.html:21: bad character U+005B '['
...

Just a quick reminder (for me as well) from the docs:

In Go templates, you can’t access array, slice, or map elements directly the same way you would in Go. For example, $.Site.Data.authors[.Params.authorkey] isn’t supported syntax.

Instead, you have to use index, a function that handles the lookup for you.

2 Likes