Search code examples
loopsgotemplates

Golang text/template sequence range


I am new in Golang. I have a problem when I want to make an HTML table using "text/template". I don't get any reference on how to make sequence numbers. What I have done so far:

<table>
    <thead>
        <tr>
            <td>#</td>
            <td>Name</td>
        </tr>
    </thead>
    <tbody>
        {{ range $index, $val := .MyList }}
        <tr>
            <td>{{ ??? }}</td>
            <td>{{ $val.Name }}</td>
        </tr>
        {{ end }}
    </tbody>
</table>

How I can get the number to start from 1? I have try {{ $index + 1 }} but get error. Please anyone can help me out?


Solution

  • Use a custom function:

    package main
    
    import (
        "html/template"
        "log"
        "os"
    )
    
    const tplDef = `
            {{ range $index, $val := .MyList }}
            <tr>
                <td>{{ $index | incr }}</td>
                <td>{{ $val.Name }}</td>
            </tr>
            {{ end }}
    `
    
    func main() {
        tpl := template.New("index")
        tpl.Funcs(map[string]interface{}{
            "incr": func(i int) int {
                return i + 1
            },
        })
        _, err := tpl.Parse(tplDef)
        if err != nil {
            log.Fatal(err)
        }
    
        type T struct {
            Name string
        }
    
        type Whatever struct {
            MyList []T
        }
    
        w := Whatever{
            MyList: []T{
                {Name: "foo"},
                {Name: "bar"},
                {Name: "baz"},
            },
        }
    
        err = tpl.Execute(os.Stdout, w)
        if err != nil {
            log.Fatal(err)
        }
    }
    

    Playground.