32

Go テンプレートで非常に単純なことを達成しようとしていますが、失敗しています!

The range action allows me to iterate through an array along with its zero-based index, as so:

{{range $index, $element := .Pages}}
  Number: {{$index}}, Text: {{element}}
{{end}}

However, I am trying to output indices that start counting from 1. My first attempt failed:

Number: {{$index + 1}}

This throws an illegal number syntax: "+" error.

I looked into the go-lang official documentation and did not find anything particular regarding the arithmetic operation inside the template.

What am I missing?

4

3 に答える 3

47

これを行うには、カスタム関数を作成する必要があります。

http://play.golang.org/p/WsSakENaC3

package main

import (
    "os"
    "text/template"
)

func main() {
    funcMap := template.FuncMap{
        // The name "inc" is what the function will be called in the template text.
        "inc": func(i int) int {
            return i + 1
        },
    }

    var strs []string
    strs = append(strs, "test1")
    strs = append(strs, "test2")

    tmpl, err := template.New("test").Funcs(funcMap).Parse(`{{range $index, $element := .}}
  Number: {{inc $index}}, Text:{{$element}}
{{end}}`)
    if err != nil {
        panic(err)
    }
    err = tmpl.Execute(os.Stdout, strs)
    if err != nil {
        panic(err)
    }
}
于 2014-09-05T17:16:10.457 に答える
18

で使用する Go テンプレートを作成しているconsul-template場合は、公開された算術関数が役立つことがあります。

Number: {{add $index 1}}
于 2015-12-31T00:49:25.027 に答える
2

HTML リストを作成する方法もありますが、すべての場合に適しているわけではありません。

<ol>
{{range $index, $element := .Pages}}
  <li>Text: {{$element}}</li>
{{end}}
</ol>

そして、それはそのようなものを生み出すことができます

  1. テキスト: 一部のページ
  2. テキスト: いくつかの別のページ
于 2021-02-02T15:26:27.027 に答える