0

这是我的代码:

m.Get("/", func(r render.Render) string {
    t := template.New("some template")
    toto := "titi"
    templateh := "<html>Hello world! {{ toto }} <form name='input' action='../first' method='post' ><input type='texte' name='toto'><input type='submit' value='Submit'></form></html>"
    t, _ = t.Parse(templateh)
    var doc bytes.Buffer
    err := t.Execute(&doc, toto)
    if err != nil {
        fmt.Println("There was an error:", err)
    }
    s := doc.String()
    fmt.Println(s)

    return s

})

它返回给我一个运行时错误:无效的内存地址或 nil 指针取消引用

我不明白为什么...

4

1 回答 1

4

通话

    t, _ = t.Parse(templateh)

返回 nil 并返回错误,说明未定义函数“todo”。模板 Execute 方法取消引用 nil 指针,导致恐慌。

你应该改变两件事:

  • 检查并处理解析调用的错误返回。这是使用template.Must辅助函数的好地方。
  • 通过替换来修复{{ todo }}模板{{.}}
于 2014-09-16T00:22:33.623 回答