Go模板中的算术

Rip*_*pul 19 go go-templates

我试图在Go模板中实现一个非常简单的事情并且失败!

range操作允许我迭代数组及其从零开始的索引,如下所示:

{{range $index, $element := .Pages}}
  Number: {{$index}}, Text: {{element}}
{{end}}
Run Code Online (Sandbox Code Playgroud)

但是,我正在尝试输出从1开始计数的索引.我的第一次尝试失败:

Number: {{$index + 1}}
Run Code Online (Sandbox Code Playgroud)

这会引发illegal number syntax: "+"错误.

我查看了go-lang官方文档,但没有找到任何与模板内部算术运算有关的内容.

我错过了什么?

che*_*eng 30

你必须编写一个自定义函数来执行此操作.

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)
    }
}
Run Code Online (Sandbox Code Playgroud)


phs*_*phs 13

如果您正在编写Go模板以供使用consul-template,您可能会发现它们的公开算术函数很有用:

Number: {{add $index 1}}
Run Code Online (Sandbox Code Playgroud)


dol*_*men 10

检查有关内置函数的文档text/template

  • len可以从字符串生成整数:{{ len "abc" }}
  • printf可以从整数生成给定长度的字符串:{{ printf "%*s" 3 "" }}
  • slice可以将字符串从整数截断为给定长度:{{ slice "abc" 0 2 }}
  • slice可以从整数中截断定长度的字符串:{{ slice "abc" 1 }}

您可以将两者结合起来以增加一个整数:

{{ len (printf "a%*s" 3 "") }}
Run Code Online (Sandbox Code Playgroud)

将产生:

4
Run Code Online (Sandbox Code Playgroud)

或者减少一个整数:

{{ len (slice (printf "%*s" 3 "") 1) }}
Run Code Online (Sandbox Code Playgroud)

显示:

2
Run Code Online (Sandbox Code Playgroud)

您还可以定义模板以重用模板片段。

因此,我们可以使用模板定义 1 个参数函数(请参阅Go Playground):

{{ define "inc" }}{{ len (printf "%*s " . "") }}{{ end -}}
{{ define "op" }}{{.}} + 1 = {{ template "inc" . }}{{ end -}}
{{ template "op" 2 }}
{{ template "op" 5 }}
Run Code Online (Sandbox Code Playgroud)

显示:

2 + 1 = 3
5 + 1 = 6
Run Code Online (Sandbox Code Playgroud)

如果模板的输入是整数数组 ( []int{4, 2, 7}),我们可以更进一步:

{{ define "inc" }}{{ len (printf "%*s " . "") }}{{ end -}}
{{ define "op" }}{{.}} + 1 = {{ template "inc" . }}{{ end -}}
{{- range . -}}
{{ template "op" . }}
{{ end -}}
Run Code Online (Sandbox Code Playgroud)

请参阅Go Playground 上的完整示例