douhui9631 2016-02-24 20:30
浏览 142
已采纳

如何使用Golang模板missingkey选项?

I would expect

t, err := template.New("t1").Option("missingkey=error").Parse("{{index . \"/foo/bar\"}}")        
err = t.Execute(os.Stdout, d)

to return an error if the map 'd' doesn't have a key '/foo/bar', but everything is just fine. Am I missing something?

Here's the go playground: http://play.golang.org/p/Oqg1Dy4h1k

  • 写回答

1条回答 默认 最新

  • duanlv2788 2016-02-24 20:40
    关注

    The missingkey option does not work with index. You will only get the desired result when you access the map using .<field-name>:

    t, err := template.New("t1").Option("missingkey=error").Parse(`{{.foo}}`)
    err = t.Execute(os.Stdout, d)
    

    You can get around this by defining your own index function that returns an error when a key is missing:

    package main
    
    import (
        "errors"
        "fmt"
        "os"
        "text/template"
    )
    
    func lookup(m map[string]interface{}, key string) (interface{}, error) {
        val, ok := m[key]
        if !ok {
            return nil, errors.New("missing key " + key)
        }
        return val, nil
    }
    
    func main() {
        d := map[string]interface{}{
            "/foo/bar": 34,
        }
        fns := template.FuncMap{
            "lookup": lookup,
        }
        t, err := template.New("t1").Funcs(fns).Parse(`{{ lookup . "/foo/baz" }}`)
        if err != nil {
            fmt.Println("ERROR 1")
        }
        err = t.Execute(os.Stdout, d)
        if err != nil {
            fmt.Println("ERROR 2")
        }
    }
    

    https://play.golang.org/p/L12lFnJig_

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)