向 golang 模板中的地图添加新键值
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 {}
但出现错误解析失败错误字符 U+005B ‘[’
感谢任何提示。
您收到的错误是因为 [
字符是意外的。
事实上,这种语法在模板中不起作用:
$json.nestedMap["action"]
您必须像这样使用 index
函数来 访问 地图元素:
index $json.nestedMap "action"
但是,据我所知,该语法不允许您实际 设置 密钥,只需访问它即可。
修改模板内映射的一种方法是在包装器结构中定义一些方法,然后从模板中调用该方法。
例如:
type mapWrapper struct {
TheMap map[string]interface{}
}
func (m *mapWrapper) SetMapValue(key, value string) string {
m.TheMap[key] = value
return ""
}
然后在模板中:
{{- .SetMapValue "key2" "value2" }}
操场上的完整工作示例:
正如@eugenioy 所说,没有 built-in 方法可以做到这一点,您需要为此使用一个函数。
幸运的是,有一个名为 Sprig 的广泛使用的 commonly-used 模板函数库,它提供:http://masterminds.github.io/sprig/dicts.html
$ 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 {}
但出现错误解析失败错误字符 U+005B ‘[’
感谢任何提示。
您收到的错误是因为 [
字符是意外的。
事实上,这种语法在模板中不起作用:
$json.nestedMap["action"]
您必须像这样使用 index
函数来 访问 地图元素:
index $json.nestedMap "action"
但是,据我所知,该语法不允许您实际 设置 密钥,只需访问它即可。
修改模板内映射的一种方法是在包装器结构中定义一些方法,然后从模板中调用该方法。
例如:
type mapWrapper struct {
TheMap map[string]interface{}
}
func (m *mapWrapper) SetMapValue(key, value string) string {
m.TheMap[key] = value
return ""
}
然后在模板中:
{{- .SetMapValue "key2" "value2" }}
操场上的完整工作示例:
正如@eugenioy 所说,没有 built-in 方法可以做到这一点,您需要为此使用一个函数。
幸运的是,有一个名为 Sprig 的广泛使用的 commonly-used 模板函数库,它提供:http://masterminds.github.io/sprig/dicts.html