【问题标题】:How to use .Key in go text/template usage如何在 go 文本/模板使用中使用 .Key
【发布时间】:2014-09-09 05:20:53
【问题描述】:

我看不懂http://golang.org/pkg/text/template/中的文档段落

- The name of a key of the data, which must be a map, preceded
  by a period, such as
    .Key
  The result is the map element value indexed by the key.
  Key invocations may be chained and combined with fields to any
  depth:
    .Field1.Key1.Field2.Key2
  Although the key must be an alphanumeric identifier, unlike with
  field names they do not need to start with an upper case letter.
  Keys can also be evaluated on variables, including chaining:
    $x.key1.key2

这是我的测试代码,但失败了。代码:http://play.golang.org/p/lbLJ4yoL2T.

var season = map[int]string{1: "spring", 2: "summer",              
        3: "autumn", 4: "winter"}                                  

func main() {                                                      
        const greeting = `Welcome, {{.Key}}`                       
        t := template.Must(template.New("greet").Parse(greeting))  
        err := t.Execute(os.Stdout, season)                        
        if err != nil {                                            
                fmt.Println(err)                                   
        }                                                          
}                                                                  

输出

Welcome, template: greet:1:11: executing "greet" at <.Key>: can't evaluate field Key in type map[int]string

【问题讨论】:

    标签: go


    【解决方案1】:

    我假设“键”是地图的键(如键/值)。此外,映射键不能是 int 以在模板中使用它。因此,不要尝试{{.Key}},而是尝试{{.a}},如fork of your playground所示:

    var season = map[string]string{"a": "spring", "b": "summer",              
            "c": "autumn", "d": "winter"}                                  
    
    func main() {                                                      
            const greeting = `Welcome, {{.a}}`                       
            t := template.Must(template.New("greet").Parse(greeting))  
            err := t.Execute(os.Stdout, season)                        
            if err != nil {                                            
                    fmt.Println(err)                                   
            }                                                          
    }                                                                  
    

    输出:

    Welcome, spring
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2023-03-06
      • 2015-01-20
      • 1970-01-01
      相关资源
      最近更新 更多