如何将当前年份添加到Go模板?

Blu*_*Sky 6 go go-templates

在Go模板中,您可以检索如下字段:

template.Parse("<html><body>{{ .Title }}</body></html>")
template.Execute(w, myObject)
Run Code Online (Sandbox Code Playgroud)

您如何"内联"当前的UTC年份?我想做这样的事情:

template.Parse("<html><body>The current year is {{time.Time.Now().UTC().Year()}}</body></html>")
Run Code Online (Sandbox Code Playgroud)

但它返回错误:

恐慌:模板:功能"时间"未定义

zzn*_*zzn 10

你可以添加功能到模板,试试这个:

package main

import (
    "html/template"
    "log"
    "os"
    "time"
)

func main() {
    funcMap := template.FuncMap{
        "now": time.Now,
    }

    templateText := "<html><body>The current year is {{now.UTC.Year}}</body></html>"
    tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
    if err != nil {
        log.Fatalf("parsing: %s", err)
    }

    // Run the template to verify the output.
    err = tmpl.Execute(os.Stdout, nil)
    if err != nil {
        log.Fatalf("execution: %s", err)
    }
}
Run Code Online (Sandbox Code Playgroud)