【问题标题】:accessing some arbitrary element in array in templates访问模板中数组中的任意元素
【发布时间】:2014-12-29 07:17:33
【问题描述】:

我需要访问模板中数组中的一些任意元素。

我有一个函数返回一个包含 3 个元素的数组,我只想访问第二个元素。我该怎么做?

模板:

test start
{{ service "mongodb" }}
test end

结果:

test start 
[0xc208062de0 0xc208062d80 0xc208062e40] 
test end

【问题讨论】:

    标签: go go-templates consul


    【解决方案1】:

    我认为预定义的全局函数 index 可以在这里提供帮助,来自包 template 的文档

    index   
    Returns the result of indexing its first argument by the
    following arguments. Thus "index x 1 2 3" is, in Go syntax,     
    x[1][2][3]. Each indexed item must be a map, slice, or array.
    

    这是一个例子;

    package main
    
    import (
        "log"
        "os"
        "text/template"
    )
    
    func returnArray(dummy string) []int {
        return []int{11, 22, 33}
    }
    
    func main() {
        funcMap := template.FuncMap{
            "myFunc": returnArray,
        }
    
        const templateText = `
        Output 0: {{myFunc "abc"}}
        Output 1: {{index (myFunc "abc") 0}}
        Output 2: {{index (myFunc "abc") 1}}
        Output 3: {{index (myFunc "abc") 2}}
        `
    
        tmpl, err := template.New("myFuncTest").Funcs(funcMap).Parse(templateText)
        if err != nil {
            log.Fatalf("parsing: %s", err)
        }
    
        err = tmpl.Execute(os.Stdout, "")
        if err != nil {
            log.Fatalf("execution: %s", err)
        }
    }
    

    输出

    Output 0: [11 22 33]
    Output 1: 11
    Output 2: 22
    Output 3: 33
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      相关资源
      最近更新 更多