• 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. }

  • 相关阅读:
    UE5和UE4版本更新重大改变汇总。
    FFmpeg开发笔记(三十)解析H.264码流中的SPS帧和PPS帧
    我的创作纪念日的温柔与七夕的浪漫交织了在一起
    c++11 多线程支持 (std::shared_future)
    仅30行代码,实现一个搜索引擎(1.0版)
    some和every
    【Spring boot 集成 servlet】
    深度学习训练基于Pod和RDMA
    (附源码)ssm产品裂变管理系统 毕业设计 100953
    分布式理论CAP
  • 原文地址:https://blog.csdn.net/tekin_cn/article/details/138903866