golang模板内的变量

前端之家收集整理的这篇文章主要介绍了golang模板内的变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
html / text模板中变量的命名空间是什么?我认为变量$x可以改变模板中的值,但是这个例子告诉我我不能.

当我试图按照年份分组锦标赛时我失败了 – 像这样(http://play.golang.org/p/EX1Aut_ULD):

package main

import (
    "fmt"
    "os"
    "text/template"
    "time"
)

func main() {
    tournaments := []struct {
        Place string
        Date  time.Time
    }{
        // for clarity - date is sorted,we don't need sort it again
        {"Town1",time.Date(2015,time.November,10,23,time.Local)},{"Town2",time.October,{"Town3",time.Date(2014,}
    t,err := template.New("").Parse(`
{{$prev_year:=0}}
{{range .}}
    {{with .Date}}
        {{$year:=.Year}}
                    {{if ne $year $prev_year}}
                        Actions in year {{$year}}:
                {{$prev_year:=$year}}
            {{end}}
    {{end}}

        {{.Place}},{{.Date}}
    {{end}}

    `)
    if err != nil {
        panic(err)
    }
    err = t.Execute(os.Stdout,tournaments)
    if err != nil {
        fmt.Println("executing template:",err)
    }
}
https://golang.org/pkg/text/template/#hdr-Variables

A variable’s scope extends to the “end” action of the control
structure (“if”,“with”,or “range”) in which it is declared,or to
the end of the template if there is no such control structure.

因此,您使用{{$prev_year:= $year}}定义的$prev_year只会生效到下一行({{end}}).

似乎没有办法解决这个问题.

执行此操作的“正确”方法是从模板中取出该逻辑,并在Go代码中进行分组.

这是一个工作示例:https://play.golang.org/p/DZoSXo9WQR

package main

import (
    "fmt"
    "os"
    "text/template"
    "time"
)

type Tournament struct {
    Place string
    Date  time.Time
}

type TournamentGroup struct {
    Year        int
    Tournaments []Tournament
}

func groupTournamentsByYear(tournaments []Tournament) []TournamentGroup {
    if len(tournaments) == 0 {
        return nil
    }

    result := []TournamentGroup{
        {
            Year:        tournaments[0].Date.Year(),Tournaments: make([]Tournament,1),},}

    i := 0
    for _,tournament := range tournaments {
        year := tournament.Date.Year()
        if result[i].Year == year {
            // Add to existing group
            result[i].Tournaments = append(result[i].Tournaments,tournament)
        } else {
            // New group
            result = append(result,TournamentGroup{
                Year: year,Tournaments: []Tournament{
                    tournament,})
            i++
        }
    }

    return result
}

func main() {
    tournaments := []Tournament{
        // for clarity - date is sorted,}

    t,err := template.New("").Parse(`
{{$prev_year:=0}}
{{range .}}
    Actions in year {{.Year}}:
    {{range .Tournaments}}

            {{.Place}},{{.Date}}
    {{end}}
    {{end}}

    `)
    if err != nil {
        panic(err)
    }
    err = t.Execute(os.Stdout,groupTournamentsByYear(tournaments))
    if err != nil {
        fmt.Println("executing template:",err)
    }
}

猜你在找的Go相关文章