Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates 使用go模板库访问特定数组索引_Templates_Go - Fatal编程技术网

Templates 使用go模板库访问特定数组索引

Templates 使用go模板库访问特定数组索引,templates,go,Templates,Go,假设我有这样一个数据结构: type Foo struct { Bar []struct { FooBar string } } 我填充它,使它有3个元素。现在,使用模板库,我如何访问该片段中第三个元素的FooBar?我尝试了以下方法,但没有成功: {Foo.Bar[2].FooBar} {Foo.Bar.2.FooBar} 现在,我知道我可以使用{.repeated section Foo.Bar}{FooBar}{.end},但这为每个元素提供了FooBar的值,而不仅仅

假设我有这样一个数据结构:

type Foo struct {
  Bar []struct {
    FooBar string
  }
}
我填充它,使它有3个元素。现在,使用
模板
库,我如何访问该片段中第三个元素的
FooBar
?我尝试了以下方法,但没有成功:

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

现在,我知道我可以使用
{.repeated section Foo.Bar}{FooBar}{.end}
,但这为每个元素提供了FooBar的值,而不仅仅是一个特定的值。我在irc上搜索和询问都没有用…

我相当肯定这是不可能的。也许有一种方法可以重组数据,使其都是命名字段


或者在实际应用程序中编写更多的逻辑。数组索引在某种程度上超出了我认为的模板包的范围。

我相当肯定这是不可能的。也许有一种方法可以重组数据,使其都是命名字段


或者在实际应用程序中编写更多的逻辑。数组索引在某种程度上超出了我认为的模板包的范围。

使用新的
text/template
html/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!"})
}

使用新的
text/template
html/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!"})
}

这就是我所做的,但这比仅仅使用模板文件中的索引要多得多。嗯……我就是这么做的,但这比仅仅使用模板文件中的索引要多得多。注意,我在新模板库存在之前问过这个问题,所以当时不可能。尽管如此,现在添加以供将来的人参考还是很好的。@Y2be我知道这一点,我也同意。请注意,我在新模板库存在之前就提出了这个问题,所以当时不可能这样做。尽管如此,现在添加这些内容以供将来的人参考还是很好的。也许我知道这一点,我也同意。