dongmubi4375 2019-03-20 16:14
浏览 865
已采纳

text / template.Templates和html / template.Templates之间的区别

Recently, I noticed that Templates() of html/template.Template works differently from the one of text/template.Template.

// go1.12
func main() {
    t := template.New( "" )
    println( len( t.Templates() ) )
}

The result of this code depends on whether you imported text/template or html/template. You'll notice that the text one prints 0 while the other prints 1. Becuase of this, I looked into the GoDoc and the html one's documentation said that Templates() includes itself -- but no further explanation. And I thought there must be some reason why; why does it have to be different from each other?

  • 写回答

1条回答 默认 最新

  • dongwu9170 2019-03-20 21:03
    关注

    Templates returned by text/template.New() and html/template.New() are both incomplete templates without a "body", they cannot yet be used to generate any output. You can verify this if you try to execute them:

    t := ttemplate.New("t")
    h := htemplate.New("h")
    fmt.Println(t.Execute(os.Stdout, nil))
    fmt.Println(h.Execute(os.Stdout, nil))
    

    Outputs (try it on the Go Playground):

    template: t: "t" is an incomplete or empty template
    template: "h" is an incomplete or empty template
    

    Returning incomplete templates in the associated templates has no significance, and is an implementation detail. One package chose to include it, the other chose not to.

    Note that if you "complete" the template definitions by actually parsing anything, both will include and return the self template in the associated templates, there is no difference in them:

    t := ttemplate.Must(ttemplate.New("t").Parse("t"))
    h := htemplate.Must(htemplate.New("h").Parse("h"))
    fmt.Println(len(t.Templates()), len(h.Templates()))
    fmt.Println(t.Execute(os.Stdout, nil))
    fmt.Println(h.Execute(os.Stdout, nil))
    

    This will output (try it on the Go Playground):

    1 1
    t<nil>
    h<nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog