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 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决