【问题标题】:Accessing specific array indices using the go template library使用 go 模板库访问特定的数组索引
【发布时间】:2011-04-23 08:59:40
【问题描述】:

假设我有这样的数据结构:

type Foo struct {
  Bar []struct {
    FooBar string
  }
}

我填充它使得 Bar 有 3 个元素。现在,使用template 库,我如何访问该切片中的第三个元素FooBar?我尝试了以下方法但没有成功:

{Foo.Bar[2].FooBar}
{Foo.Bar.2.FooBar}

现在,我知道我可以使用{.repeated section Foo.Bar} {FooBar} {.end},但这为我提供了 每个 元素的 foobar 值,而不仅仅是一个特定的元素。我用谷歌搜索并在 irc 上询问无济于事......

【问题讨论】:

    标签: templates go


    【解决方案1】:

    使用新的text/templatehtml/template

    package main
    
    import (
        "fmt"
        "text/template" // or html/template
        "os"
    )
    
    func main() {
        tmpl, err := template.New("name").Parse("{{index . 0}}")
        if err != nil {
            fmt.Println(err)
            return
        }
        tmpl.Execute(os.Stdout, []string{"yup, that's me", "not that!"})
    }
    

    【讨论】:

    • 请注意,我在新模板库存在之前就问过这个问题,所以当时不可能。不过,现在添加还是不错的,供以后的人参考。
    • @crazy2be 我知道,我同意。
    【解决方案2】:

    我很确定这是不可能的。也许有一种方法可以重组数据,使其全部成为命名字段。

    或者只是在您的实际应用程序中编写更多逻辑。数组索引有点超出了我认为的模板包的范围。

    【讨论】:

    • 这就是我所做的,但它比仅使用模板文件中的索引要多得多。嗯……
    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2017-06-07
    • 2021-03-29
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多