当前位置:   article > 正文

golang template: “xxx.html“ is an incomplete or empty template 解决方法

golang template: “xxx.html“ is an incomplete or empty template 解决方法

这个异常一般是因为在使用 template.New("xxx.html") 时这里的名称非真实存在的视图文件名导致, 这个地方有点坑, 明明ParseFiles函数已经指定了视图路径了,而这里的New里面的名字居然还必须是你后面指定的视图路径中的文件名!  

     解决方法就是将 template.New("xxx.html") 这里的xxx.html改为你的真实存在的视图文件的名称。 注意必须是包含后缀的文件名

导致这个问题的原因是Template里面的这escape方法,代码如下:

  1. // escape escapes all associated templates.
  2. func (t *Template) escape() error {
  3. t.nameSpace.mu.Lock()
  4. defer t.nameSpace.mu.Unlock()
  5. t.nameSpace.escaped = true
  6. if t.escapeErr == nil {
  7. if t.Tree == nil {
  8. return fmt.Errorf("template: %q is an incomplete or empty template", t.Name())
  9. }
  10. if err := escapeTemplate(t, t.text.Root, t.Name()); err != nil {
  11. return err
  12. }
  13. } else if t.escapeErr != escapeOK {
  14. return t.escapeErr
  15. }
  16. return nil
  17. }
  18. // Execute applies a parsed template to the specified data object,
  19. // writing the output to wr.
  20. // If an error occurs executing the template or writing its output,
  21. // execution stops, but partial results may already have been written to
  22. // the output writer.
  23. // A template may be executed safely in parallel, although if parallel
  24. // executions share a Writer the output may be interleaved.
  25. func (t *Template) Execute(wr io.Writer, data any) error {
  26. if err := t.escape(); err != nil {
  27. return err
  28. }
  29. return t.text.Execute(wr, data)
  30. }
  31. // ExecuteTemplate applies the template associated with t that has the given
  32. // name to the specified data object and writes the output to wr.
  33. // If an error occurs executing the template or writing its output,
  34. // execution stops, but partial results may already have been written to
  35. // the output writer.
  36. // A template may be executed safely in parallel, although if parallel
  37. // executions share a Writer the output may be interleaved.
  38. func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error {
  39. tmpl, err := t.lookupAndEscapeTemplate(name)
  40. if err != nil {
  41. return err
  42. }
  43. return tmpl.text.Execute(wr, data)
  44. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/607535
推荐阅读
相关标签
  

闽ICP备14008679号