crazy2be
crazy2be

Reputation: 2252

Accessing specific array indices using the go template library

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...

Upvotes: 1

Views: 564

Answers (2)

Zippo
Zippo

Reputation: 16420

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!"})
}

Upvotes: 3

cthom06
cthom06

Reputation: 9635

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.

Upvotes: 1

Related Questions