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

  • 相关阅读:
    Flink-Java报错之org.apache.flink.api.common.functions.InvalidTypesException
    linux高级---k8s中的五种控制器
    【TikTok】美区TK矩阵引流系统有哪些深度测评方案?
    运筹学基础【三】 之 决策
    Kafka3.x安装以及使用
    ThreadPoolExecutor线程池原理
    【双碳】Acrel-1000DP分布式光伏并网及数据采集与控制的方式
    javascript二维数组(16)去除空格
    卷积神经网络参数量和计算量的计算
    Mac下根目录和家目录的区别
  • 原文地址:https://blog.csdn.net/tekin_cn/article/details/138903866