【问题标题】:Go templates: How do I access array item (arr[2]) in templates?Go 模板:如何访问模板中的数组项 (arr[2])?
【发布时间】:2015-09-22 23:19:44
【问题描述】:

如何访问模板中的数组项(例如 a[2])?

每当我这样做时,我都会收到“bad character U+005B '['”

{{ .a[2] }}

【问题讨论】:

    标签: templates go beego


    【解决方案1】:

    您需要使用index模板函数。

    {{index .a 2}}
    

    【讨论】:

    • 要访问数组项上的字段,请使用{{ (index .a 2).field }}
    • @webwurst 如果字段是变量怎么办? .$field 不起作用
    • @TomSawyer 将其包裹在另一个索引中 {{ index (index .a 2) $field }}
    【解决方案2】:

    以 *.yaml 格式访问数组项上的字段:

    {{ (index .Values.fields 0).fieldItem }}
    

    0(0) 的索引作为 fieldItem 的字段数组。

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 2011-04-23
      • 1970-01-01
      • 2019-02-22
      相关资源
      最近更新 更多