0

下面的代码在tmp.Executefunction "copyrightYear" not defined

import (
    "os"
    "html/template"
    "fmt"
)

func main() {
    fm := template.FuncMap{
        "copyrightYear": func() string {
            return fmt.Sprintf("%d", time.Now().Year())
        },
    }
    tmp := template.Must(template.New("").Parse("{{copyrightYear}}")).Funcs(fm)
    tmp.Execute(os.Stdout, nil)
}

我错过了什么?我已经浏览了文档。将其更改为call copyrightYear在模板中,或copyrightYear .不修复它。

4

1 回答 1

1
package main

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

func main() {
        fm := template.FuncMap{
                "copyrightYear": func() string {
                        return fmt.Sprintf("%d", time.Now().Year())
                },
        }
        tmp := template.Must(template.New("").Funcs(fm).Parse("{{copyrightYear}}"))
        tmp.Execute(os.Stdout, nil)
}

操场


输出:

2009
于 2013-07-10T12:50:29.627 回答