Go language template, Text/template package

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Defining a template is the simplest alternative package mainimport that embeds a set of text into another set of text (string--)."OS"    "Text/template") Func main () {Name: ="China"Tmpl, err: = template. New ("Test"). Parse ("Hello, {{.}}")//Create a template with the content "Hello, {{.}}"    ifErr! = 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 {{.} }    //Composite results are placed on the OS. StdOut.    ifErr! = Nil {panic (err)}}//output: Hello, WaynehuBecause"Hello, {{.}}"is also a string, so can be carried out separately, as follows://This sentenceTmpl, err: = template. New ("Test"). Parse ("Hello, {{.}}")//equal to the following two sentencesMuban: ="Hello, {{.}}"Tmpl, err: = template. New ("Test"). Parse (muban)//The following examples are expressed in two sentencesIncomingstructTemplate synthesis that sentence, the first2A parameter isInterface{}, so you can pass in any type and now pass instructLook to getstructValue, just use the member name to see the code: Package Mainimport ("OS"    "Text/template") type Inventory struct {Material string Count uint}func main () {sweaters: = inventory{"Wool", -} muban: ="{{. Count}} items are made of {{. Material}} "Tmpl, err: = template. New ("Test"). Parse (muban)//Create a template    ifErr! = Nil {panic (err)} err = Tmpl. Execute (OS. Stdout, sweaters)//combine the struct with the template, and the resultant result is placed on the OS. StdOut.    ifErr! = Nil {panic (err)}}//output: All items are made of woolMulti-template, Introduction new,name,lookup//A template can have multiple, with name to distinguishMuban_eng: ="{{. Count}} items are made of {{. Material}} "Muban_chn: ="{{. Material}} has done {{. Count}} Items "//Create a template with the name of China, the content of the template is Muban_chn stringTmpl, err: = template. New ("China") Tmpl, err = Tmpl. Parse (MUBAN_CHN)//Create a template name is 中文版, the content of the template is Muban_eng stringTmpl, err = Tmpl. New ("中文版") Tmpl, err = Tmpl. Parse (Muban_eng)//combine the struct with the template, synthesize it with the template named China, and put the result into the OS. StdOut, the content of "wool did 17 projects."Err = Tmpl. Executetemplate (OS. Stdout,"China", sweaters)//combine the struct with the template, synthesize it with the template named China, and put the result into the OS. In stdout, the content is "made of wool"Err = Tmpl. Executetemplate (OS. Stdout,"中文版", sweaters) Tmpl, err = template. New ("中文版") FMT. Println (Tmpl. Name ())//Print out 中文版Tmpl, err = Tmpl. New ("China") FMT. Println (Tmpl. Name ())//Print out ChinaTmpl=tmpl. Lookup ("中文版")//must have a return, otherwise it will not take effectFmt. Println (Tmpl. Name ())//Print out 中文版File templates, introducing Parsefiles//template can be a rowMuban: ="{{. Count}} items are made of {{. Material}} "//can also be multi-lineMuban: = ' Items number is {{. Count}}there made of{{. Material}} ' put the content of the template in a text file, use the text file in the time to assign all the contents of the Muban this variable can be implemented on their own, but in fact, the Tamplate package has helped us encapsulate, that is the template. The Parsefiles method assumes that there is a file mb.txt the contents of the muban variable $cat mb.txt{{. Count}} items are made of{{. Material}} So Below2Line muban: ="{{. Count}} items are made of {{. Material}} "Tmpl, err: = template. New ("Test"). Parse (muban)//Create a templateEquivalent to Tmpl, err: = template. Parsefiles ("Mb.txt")//Create a template where new ("name") is not required, because name is automatically file nameFile template, Introduction Parseglobparsefiles accepts a string, the content of the string is the path to a template file (absolute pathorRelative path) Parseglob is also similar, is to use a regular way to match multiple files assuming a directory has a.txt b.txt c.txt words with parsefiles need to write3Line corresponding3Files and if there are 10,000 files? And with Parseglob just write Template.parseglob ("*.txt") to the output of the template, there are several sets of templates under the Executetemplate and execute templates, with a set of templates that the current template can use to view the current template err = Tmpl. Executetemplate (OS. Stdout,"中文版", sweaters)//Specify the template name, this time for 中文版Err = Tmpl. Execute (OS. Stdout, sweaters)//template name omitted, the current template is printedTemplates can be used in the template reuse template, in order to achieve the reuse purposes, with the template keyword muban1: = ' Hi, {{Template"M2"}},hi, {{Template"M3"}} ' muban2: ="I am a template 2,{{template"M3"}}"MUBAN3: ="Ha I am template 3ha!"Tmpl, err: = template. New ("M1"). Parse (Muban1) Tmpl. New ("M2"). Parse (muban2) Tmpl. New ("M3"). Parse (muban3) Err = Tmpl. Execute (OS. Stdout, nil) complete 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)ifErr! = Nil {panic (err)} Tmpl. New ("M2"). Parse (MUBAN2)ifErr! = Nil {panic (err)} Tmpl. New ("M3"). Parse (MUBAN3)ifErr! = Nil {panic (err)} err = Tmpl. Execute (OS. Stdout, Nil)ifErr! = Nil {panic (err)}} Output content Hi, I am the template2, ha I am a template3Ha!,hi, ha I'm a template3ha! template's carriage return template file 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 order in the standard library example (template) written or a little messy, I sorted as follows: Const LETTER = ' Dear {. name}},{{if. Attended}}it was a pleasure toSee your at the wedding. If attended istrue, this sentence is the second line {{Else}}it is a shame you couldn ' t make It toThe wedding. If attended isfalse, this sentence is the second line {{End}}{{ with. Gift}}thank forThe lovely {{.}}. {{End}}best Wishes,josie ' Explanation: Dear a dear should be in the first line, so in front of D can not have a carriage return, or Dear will run to the2OK, so dear to cling to 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 the carriage return is wrapped inif, become part of the text, so the layout error-prone correct text layout as follows if the body of a line, to thetrueAndfalseAll of the content is written on a single line such as {{if. attended}}trueLine,hellotrue{{Else}}falseLine,hifalse{{End}} If the body has more than one line, it is equivalent to splitting a row into multiple rows to discovertrueThe last line andfalseThe first line is in the same row {{if. attended}} and the first line of ture in the same row {{End}} andfalseThe last line in the same line as the following {{if. attended}}trueLinehellotrue{{Else}}falseLinehifalse{{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. withcorresponding to theEndTo write in the first2Line, will be "Thank you" this sentence behind take a carriage return into, so the wording, like "Thank You" This sentence is inserted in the text below the only so write, whether there is no "Thank you", the text and best wishes, always only1Line 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.