【问题标题】:Custom template functions not found in html template [duplicate]html模板中找不到自定义模板功能[重复]
【发布时间】:2018-12-29 17:41:47
【问题描述】:

我这样渲染模板:

  func renderTemplate(...........) {
    rt := template.Must(template.ParseFiles(
        fmt.Sprintf("%s/%s", templatesPath, baseLayoutPath),
        fmt.Sprintf("%s/%s", templatesPath, tplName)))

      err := rt.ExecuteTemplate(w, "base", nil)
      //[................]
  }

我想在里面注册一个自定义函数:

func myTest1(string s) string {
  return "hello: " + s
}


func renderTemplate(...........) {
  rt := template.Must(template.ParseFiles(
              fmt.Sprintf("%s/%s", templatesPath, baseLayoutPath),
              fmt.Sprintf("%s/%s", templatesPath, tplName))).Funcs(template.FuncMap{"test1": myTest1})

这不起作用:"test1" not defined"

  // html template:


  {{range .items}}

    {{.Field1 | test1}}

为什么不以及如何让它发挥作用?

【问题讨论】:

    标签: html go


    【解决方案1】:

    在解析模板之前添加模板函数。

    来自html/template docs for Funcs()

    Funcs 将参数映射的元素添加到模板的函数映射。必须在模板解析之前调用。

    funcMap := template.FuncMap{"test1":myTest1}
    rt := template.Must(template.New("name").Funcs(funcMap).ParseFiles(
              fmt.Sprintf("%s/%s", templatesPath, baseLayoutPath),
              fmt.Sprintf("%s/%s", templatesPath, tplName)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 2012-06-24
      • 1970-01-01
      • 2011-06-27
      相关资源
      最近更新 更多