duannaxin9975 2014-09-09 05:20
浏览 4
已采纳

如何在Go文本/模板用法中使用.Key

I don't understand the document paragraph in 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

Here is my test code, but failed. code: 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)                                   
        }                                                          
}                                                                  

Output

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

1条回答 默认 最新

  • doushan2811 2014-09-09 05:24
    关注

    I'd assume "Key" is the key (as in key/value) of the map. Also, the map keys can't be an int to use it in the template like that. So instead of {{.Key}} try {{.a}} as shown in this 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)                                   
            }                                                          
    }                                                                  
    

    Output:

    Welcome, spring
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测