Go template name

前端 未结 2 495
别跟我提以往
别跟我提以往 2020-12-01 23:14

In the html/template (and text/template) packages, template.New has the following signature:

func New(name string) *Template
         


        
2条回答
  •  日久生厌
    2020-12-02 00:11

    It is used to render associated templates.

    For instance:

    tmpl := template.Must(template.New("body").Parse(`
        {{ define "body" }}
           Body
        {{ end }}
        `))
    
    tmpl = template.Must(tmpl.New("base").Parse(`
         Start of base template
    
         {{ template "body" }}
    
         End of base template
        `))
    
    tmpl = template.Must(tmpl.New("baz").Parse(`
         Start of baz template
    
         {{ template "body" }}
    
         End of baz template
        `))
    
    tmpl.ExecuteTemplate(os.Stdout, "base", nil)
    tmpl.ExecuteTemplate(os.Stdout, "baz", nil)
    

    Play Example

    Output:

         Start of base template
    
    
           Body
    
    
         End of base template
    
         Start of baz template
    
    
           Body
    
    
         End of baz template
    

    tmpl.ExecuteTemplate(os.Stdout, "base", nil) will render the template using the "base" template

    tmpl.ExecuteTemplate(os.Stdout, "baz", nil) will render the template using the "baz" template

提交回复
热议问题