Szukaj…


Składnia

  • t, err: = template.Parse ( {{.MyName .MyAge}} )

  • t.Execute (os.Stdout, struct {MyValue, MyAge string} {„John Doe”, „40.1”})

Uwagi

Golang zapewnia pakiety takie jak:

  1. text/template

  2. html/template

zaimplementować oparte na danych szablony do generowania wyników tekstowych i HTML.

Wartości wyjściowe zmiennej struct na Standard Output za pomocą szablonu tekstowego

package main

import (
    "log"
    "text/template"
    "os"
)

type Person struct{
    MyName string
    MyAge int
}

var myTempContents string= `
This person's name is : {{.MyName}}
And he is {{.MyAge}} years old.
`

func main() {
    t,err := template.New("myTemp").Parse(myTempContents)
    if err != nil{
        log.Fatal(err)
    }
    myPersonSlice := []Person{ {"John Doe",41},{"Peter Parker",17} }
    for _,myPerson := range myPersonSlice{
        t.Execute(os.Stdout,myPerson)
    }
}

Plac zabaw

Definiowanie funkcji wywoływania z szablonu

package main

import (
    "fmt"
    "net/http"
    "os"
    "text/template"
)

var requestTemplate string = `
{{range $i, $url := .URLs}}
{{ $url }} {{(status_code $url)}}
{{ end }}`

type Requests struct {
    URLs []string
}

func main() {
    var fns = template.FuncMap{
        "status_code": func(x string) int {
            resp, err := http.Head(x)
            if err != nil {
                return -1
            }
            return resp.StatusCode
        },
    }

    req := new(Requests)
    req.URLs = []string{"http://godoc.org", "http://stackoverflow.com", "http://linux.org"}

    tmpl := template.Must(template.New("getBatch").Funcs(fns).Parse(requestTemplate))
    err := tmpl.Execute(os.Stdout, req)
    if err != nil {
        fmt.Println(err)
    }
}

Tutaj używamy naszej zdefiniowanej funkcji status_code aby uzyskać kod statusu strony internetowej bezpośrednio z szablonu.

Wynik:

http://godoc.org 200

http://stackoverflow.com 200

http://linux.org 200


Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow