使用Go模板库访问特定的数组索引

huangapple go评论99阅读模式
英文:

Accessing specific array indices using the go template library

问题

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

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

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

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

我知道我可以使用{.repeated section Foo.Bar} {FooBar} {.end},但这会给我每个元素的foobar值,而不仅仅是一个特定的元素。我已经在谷歌上搜索和在IRC上询问了,但没有结果...

英文:

Say i have a data structure like this:

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

And i fill it such that Bar has 3 elements. Now, using the template library, how can i access say the 3rd element's FooBar in that slice? I have tried the following with no success:

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

Now, i know that i can use {.repeated section Foo.Bar} {FooBar} {.end}, but that gives me the value of foobar for each element, rather than just a specific one. I have googled and asked on irc to no avail...

答案1

得分: 3

使用新的text/templatehtml/template

package main

import (
	"fmt"
	"text/template" // 或者 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{"是的,那是我", "不是那个!"})
}
英文:

Using the new text/template or 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!"})
}

答案2

得分: 1

我相当确定这是不可能的。也许你可以重新组织你的数据,使其成为具有命名字段的形式。

或者在你的实际应用程序中编写更多的逻辑。我认为数组索引在模板包的范围之外。

英文:

I'm fairly certain this just isn't possible. Perhaps there's a way you could restructure your data so that it's all named fields.

Or just write some more logic in your actual application. Array indexing is somewhat beyond the scope of the template package I would think.

huangapple
  • 本文由 发表于 2010年10月10日 12:06:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/3898975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定