模板:1: 函数 “copyrightYear” 未定义

huangapple go评论62阅读模式
英文:

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 copyrightYearcopyrightYear .并不能解决问题。

英文:

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)
}

Playground


Output:

2009

huangapple
  • 本文由 发表于 2013年7月10日 20:43:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/17570977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定