英文:
Template :1: function "copyrightYear" not defined
问题
以下是翻译好的部分:
以下代码在tmp.Execute处发生恐慌,显示函数“copyrightYear”未定义
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 .并不能解决问题。
英文:
The following code panics at tmp.Execute saying function "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)
}
What am I missing? I've poked around the documentation.  Changing it to call copyrightYear in the template, or copyrightYear . doesn't fix it.
答案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)
}
英文:
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)
}
Output:
2009
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论