$ 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.
The error you are getting is because the [
character is unexpected.
Indeed, this syntax does not work inside templates:
$json.nestedMap["action"]
You must instead use the index
function like this to access a map element:
index $json.nestedMap "action"
But, AFAIK that syntax would not allow you to actually set the key, just access it.
One way to modify the map inside a template would be to define some method in a wrapper struct then call that method from the template.
For example:
type mapWrapper struct {
TheMap map[string]interface{}
}
func (m *mapWrapper) SetMapValue(key, value string) string {
m.TheMap[key] = value
return ""
}
Then in the template:
{{- .SetMapValue "key2" "value2" }}
Full working example on playground: