Hugo模板:如何通过插值设置dict的键值?
在Hugo(Go模板)中修改Dict单个条目值的方法
Go模板中的dict是不可变的,无法直接修改已创建dict的键值对,必须通过重新构建新dict的方式实现需求。这里推荐用Hugo内置的merge函数来高效完成,它会用新dict的键值覆盖原dict的同名键,同时保留其他原有键值。
修正后的代码示例
<figure class="histogram"> {{ $vitality := dict "institutional" .Params.count_institutional "stable" .Params.count_stable "endangered" .Params.count_endangered "dying" .Params.count_dying "extinct" .Params.count_extinct }} {{ if ne .Params.vitality "" }} <!-- 生成仅包含目标键值的临时dict,再与原dict合并 --> {{ $update := dict .Params.vitality 1 }} {{ $vitality = merge $vitality $update }} {{ end }} {{ range $key, $value := $vitality }} <div class="histogram-bar" data-category="{{ $key }}" data-count="{{ $value }}"> <div class="histogram-bar-label">{{ $key }}</div> </div> {{ end }} </figure>
关键说明
- 变量重新赋值用
=而非:=::=仅用于首次声明变量,后续修改值要用=。 merge函数的作用:合并两个dict,新dict中的键会覆盖原dict的同名键,完美适配“修改单个键值”的需求。
如果不想依赖merge函数,也可以手动重新构建整个dict(逐个判断键是否匹配目标键,替换对应值),但这种方式代码冗余,仅在特殊场景下使用,示例如下:
<figure class="histogram"> {{ $targetKey := .Params.vitality }} {{ $vitality := dict "institutional" (if eq $targetKey "institutional" 1 .Params.count_institutional) "stable" (if eq $targetKey "stable" 1 .Params.count_stable) "endangered" (if eq $targetKey "endangered" 1 .Params.count_endangered) "dying" (if eq $targetKey "dying" 1 .Params.count_dying) "extinct" (if eq $targetKey "extinct" 1 .Params.count_extinct) }} {{ range $key, $value := $vitality }} <div class="histogram-bar" data-category="{{ $key }}" data-count="{{ $value }}"> <div class="histogram-bar-label">{{ $key }}</div> </div> {{ end }} </figure>
内容的提问来源于stack exchange,提问作者Merchako
相关产品推荐
相关产品推荐

