Go text/templete templates

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

Take the time to go to the Text/templete template finishing study, now summarized under.
Steps
1. Define data types

type Opt struct{    Name string    Age int    Score float32}oneOpt{"xiao chao",26,90}twoOpt{"xiao er",29,89}

2. Create a template

    one_str := "one_str :my name is {{.Name}},and age is {{.Age}},my score is {{.Score}}."    two_str := "two_str :my name is {{.Name}},and age is {{.Age}},my score is {{.Score}}."   t1 := template.New("one1")   t2 := template.New("two2")

3. Parsing templates

     t1,_ = t1.Parse(one_str)     t2,_ = t2.Parse(two_str)

4. Execute the template

        t1.ExecuteTemplate(os.Stdout,"one1",one)        println("\n")        t2.ExecuteTemplate(os.Stdout,"two2",two)

Full code:

 PackageMainimport ("OS"    "Text/template")typeOpt struct{NamestringAge int score Float32}func main () {/* Stu: = opt{"Zhao Zi Long", -, About} Tmpl, err: = template. New ("Stu"). Parse ("Hello, name:{{." name}},age:{{. age}},score:{{. Score}} ")//Create a template that contains"Hello, {{.}}"TMP2,ERR2: = template. New (""). Executetemplate ()ifErr! =Nil{Panic (err)} err = Tmpl. Execute (OS. Stdout, Stu)//WillstringWith template composition, the contents of the variable name are replaced by {{.}} The results of the synthesis are placedOS. StdOut.ifErr! =Nil{Panic (ERR)} */One: = opt{"Xiao Chao", -, -}: = opt{"Xiao er", in, the} ONE_STR: ="One_str:my name is {. Name}},and age is {{. Age}},my score is {. Score}}. "TWO_STR: ="Two_str:my name is {. Name}},and age is {{. Age}},my score is {. Score}}. "T1: = template. New ("One1") T2: = template. New ("TWO2") t1,_ = t1. Parse (one_str) t2,_ = t2. Parse (TWO_STR) t1. Executetemplate (OS. Stdout,"One1", one) println ("\ n") T2. Executetemplate (OS. Stdout,"TWO2", both)}
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.