Khoa Nguyen
Khoa Nguyen

Reputation: 1600

Add new key value to a map in golang template

$ 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.

Upvotes: 1

Views: 4200

Answers (2)

FGM
FGM

Reputation: 2860

As @eugenioy said, there is no built-in way to do this, and you need to use a function for that.

Luckily, there's a widespread library of commonly-used templates functions called Sprig, which provides that: http://masterminds.github.io/sprig/dicts.html

Upvotes: 1

eugenioy
eugenioy

Reputation: 12393

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:

https://play.golang.org/p/8bT4jjYwuzg

Upvotes: 2

Related Questions