Go language template, Text/template package

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go language template, Text/template package

Defined

A template is a set of text embedded in another set of text

The simplest replacement for incoming string--

 package mainimport (" OS "" text/template ") func Main () {name: =  "Waynehu" Tmpl, err: = template. New ( "test"). Parse ( "Hello, {{.}}") //create a template with the content "Hello, {{.}}" if err! = nil {panic (err)} err = Tmpl. Execute (OS. Stdout, name) //the string is composited with the template, and the contents of the variable name are replaced by {{.}} //compositing results to the OS. StdOut if err! = nil {panic (err )}}//output: Hello, Waynehu         

Because it "hello, {{.}}" is also a string, it can be carried out separately, as follows:

template.New("test").Parse("hello, {{.}}")//等于下面的两句muban := "hello, {{.}}"tmpl, err := template.New("test").Parse(muban)//之后的例子都用两句的方式表达

Incoming struct

Template composition that sentence, the 2nd parameter is interface{}, so you can pass in any type, now pass in the struct to see to get the value of the struct, just use the member name, see the code:

Package MainImport ("OS""Text/template")type Inventory struct {Material  String Count uint}func main () {sweaters: = Inventory{ "wool", 17} muban: =  "{{. Count}} items are made of {{. Material}} "Tmpl, err: = template. New ( "test"). Parse (muban) //Create a template if err! =  Nil {panic (err)} err = Tmpl. Execute (OS. Stdout, sweaters) //the composition of the struct with the template, the result of which is put into the OS. StdOut if err! = nil {panic (err )}}//output: All items are made of wool        

Multi-template, Introduction new,name,lookup

A template can have multiple, with name to differentiate Muban_eng: ="{{. Count}} items are made of {{. Material}} "Muban_chn: ="{{. Material}} has done {{. Count}} Items "To create a template with the name of China, the content of the template is Muban_chn string Tmpl, err: = template.New("China") tmpl, err = Tmpl.Parse(MUBAN_CHN)The name of the created template is 中文版, the content of the template is Muban_eng string tmpl, err = Tmpl.New("中文版") tmpl, err = Tmpl.Parse(Muban_eng)The composition of the struct and template is synthesized by the template named China, and the result is put into the OS. STDOUT, content for "wool made 17 items" Err = Tmpl.Executetemplate(OS. Stdout,"China", sweaters)The composition of the struct and template is synthesized by the template named China, and the result is put into the OS. In stdout, the content is "made of wool" err = Tmpl.Executetemplate(OS. Stdout,"中文版", sweaters) tmpl, err = template.new ( "中文版") Fmt.println//print out englishtmpl, err = Tmpl. new ( "China") Fmt. println (Tmpl. Name ()) //print out Chinatmpl=tmpl. lookup ( "中文版") //must have a return, otherwise it will not take effect to FMT. println (Tmpl. Name ()) //print out 中文版          

File templates, introducing Parsefiles

//模板可以是一行muban := "{{.Count}} items are made of {{.Material}}"//也可以是多行muban := `items number is {{.Count}}there made of {{.Material}}`

The content of the template is sent to a text file, when used to assign all the contents of the text file to muban this variable can be
The above ideas can be implemented on their own, but in fact the Tamplate package has helped us encapsulate, that is the template. Parsefiles method

假设有一个文件mb.txt的内容是muban变量的内容$cat mb.txt{{.Count}} items are made of {{.Material}}那么下面2行muban := "{{.Count}} items are made of {{.Material}}"tmpl, err := template.New("test").Parse(muban) //建立一个模板等价于tmpl, err := template.ParseFiles("mb.txt") //建立一个模板,这里不需要new("name")的方式,因为name自动为文件名

File templates, introducing Parseglob

Parsefiles accepts a string, the content of the string is the path to a template file (absolute path or relative path)
Parseglob is also similar, is to use regular way to match multiple files

假设一个目录里有a.txt b.txt c.txt的话用ParseFiles需要写3行对应3个文件,如果有一万个文件呢?而用ParseGlob只要写成template.ParseGlob("*.txt") 即可

Template output, introducing Executetemplate and Execute

There are multiple templates under the template, with a set of templates that are the current template
You can view the current template by using name

err = tmpl.ExecuteTemplate(os.Stdout, "english", sweaters)  //指定模板名,这次为englisherr = tmpl.Execute(os.Stdout, sweaters) //模板名省略,打印的是当前模板

Reuse of templates

Templates can be used to set up templates for reuse purposes, using the template keyword

muban1 := `hi, {{template "M2"}},hi, {{template "M3"}}`muban2 := "我是模板2,{{template "M3"}}"muban3 := "ha我是模板3ha!"tmpl, err := template.New("M1").Parse(muban1)tmpl.New("M2").Parse(muban2)tmpl.New("M3").Parse(muban3)err = tmpl.Execute(os.Stdout, nil)

Full code:

Package MainImport ("OS""Text/template") func main () {muban1: = ' Hi, {{Template"M2"}},hi, {{Template"M3"}} ' muban2: = ' I am a template2,{{Template"M3"}} ' muban3: = "ha I am template 3ha!" Tmpl, err: = template. New ( "M1").  Parse (muban1) if err! = nil {Panic (err)} Tmpl.new ( Parse (muban2) if err! = nil {Panic (err)} Tmpl.new ( Parse (MUBAN3) if err! = nil {Panic (err)} err = Tmpl.execute (Os. Stdout, nil) if err! = nil {Panic ( ERR)}}                

Content of the output

hi, 我是模板2,ha我是模板3ha!,hi, ha我是模板3ha!

Carriage return of the template

Template files in the carriage return is also part of the template, if the return position control is not good, the composition of the article will be out of shape in the standard library example (template) written or a little messy, I tidy up as follows:

Const LETTER = ' Dear{{. Name}},{{if  . Attended}}it is a pleasure to see you at the wedding. If attended is true, this sentence is the second line {{else}}It is a shame You couldn ' t do it to the wedding. If attended is false, this is the second line {{ end}} {{with Span class= "hljs-variable". Gift}}thank you for the lovely {{.}} {{end}}best Wishes,Josie '   

Explain:

    • Dear某某某The dear should be on the first line, so D you can't have a carriage return in front, or you Dear 'll run to line 2nd.
      • So Dear cling to the "'
    • The name of the letter obeyed and the body has a line of blank line, it is best to explicitly hit a line, and the standard library of carriage return is wrapped in the if, as part of the text, so the layout error-prone
    • The correct text layout is as follows
      • If the body is a line, write all the contents of true and false in one line
        • For example, {{if. Attended}}true Line,hello true{{else}}false Line,hi False{{end}}
      • If the body has more than one line, it is equivalent to splitting a row into multiple lines
        • You will find that the first line of true last line and false is on the same line
        • {{If.} attended}} and the first line of ture on the same line
        • The last line of {{end}} and False is on the same line

As follows

{{if .Attended}}true linehello true{{else}}false linehi false{{end}}
    • About {{with .Gift}} , meaning that if gift is not empty, the entire line is printed, and if it is empty, it is not printed
      • Only in this way, with the corresponding end to write in the 2nd line, will be "Thank you" after the sentence with a carriage enter, so the wording, like "Thank You" This sentence is inserted in the text below the
      • The only way to write, whether there is no "Thank you", the text and best wishes, is always only 1 lines blank
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.