【问题标题】:error: template: "..." is an incomplete or empty template错误:模板:“...”是不完整或空的模板
【发布时间】:2018-03-01 05:42:35
【问题描述】:

我正在尝试将FuncMap 添加到我的模板中,但收到以下错误:

模板:“foo”不完整或为空 模板

在我使用 FuncMap 之前,模板的解析工作得很好,所以我不确定为什么现在会抛出错误。

这是我的代码:

funcMap := template.FuncMap{
    "IntToUSD": func(num int) string {
        return decimal.New(int64(num), 2).String()
    },
}

// ...

tmpl, err := template.New(t.file).Funcs(funcMap).ParseFiles(t.files()...)
if err != nil {
    // ...
}

t.files() 只返回一段字符串,它们是文件路径。

有人知道怎么回事吗?

【问题讨论】:

  • t.file 是 t.files() 中文件之一的基本名称吗? (请参阅ParseFiles doc 中的要求)
  • 你是说template.New(t.file).ParseFiles(t.files()...) 工作正常但template.New(t.file).Funcs(funcMap).ParseFiles(t.files()...) 失败?
  • @muistooshort 不,实际上我说错了,template.ParseFiles(t.files()...) 工作正常,当我使用 template.New(...) 语法时它失败了。
  • @jrefior 不,不是,很好,我会尝试检查。

标签: go


【解决方案1】:

确保您传递给template.New 的参数是您传递给ParseFiles 的列表中文件之一的基本名称。

一个选项是

files := t.files()
if len(files) > 0 {
    name := path.Base(files[0])
    tmpl, err := template.New(name).Funcs(funcMap).ParseFiles(files...)

ParseFiles documentation:

由于 ParseFiles 创建的模板由参数文件的基本名称命名,因此 t 通常应该具有文件的(基本)名称之一的名称。

【讨论】:

  • 谢谢你,我认为这可能是问题,因为我只是使用随机模板名称。回家后我会尝试,如果解决了问题,我会接受答案。
  • 就是这样。再次感谢。
  • 如果我使用 template.Must(template.New("").Funcs(fm).ParseFiles("test.gohtml") 会怎样??回答:-NO 但为什么呢?
  • 仅供参考,它对我不起作用,因为名称不包含文件扩展名。一旦我添加了扩展,它就起作用了。
  • @RujalShrestha template.Must(template.New("").Funcs(fm).ParseFiles("test.gohtml") 如果您使用 err = tpl.ExecuteTemplate(os.Stdout, "test.gohtml", data) 而不是 err = tpl.Execute(os.Stdout, data) 确实有效。基本上,模板名称必须在某处指定。
【解决方案2】:

我遇到了同样的问题。我意识到了

tmpl, err := template.New("").Funcs(funcMap).ParseFiles("fileName")

如果你使用它也可以

err := tpl.ExecuteTemplate(wr, "fileName", data)

如果我使用

err := tpl.Execute(wr, data)

那么我应该在New()中指定模板名称:

tmpl, err := template.New("fileName").Funcs(funcMap).ParseFiles("fileName")

【讨论】:

    【解决方案3】:

    你也可以使用 Template.Must 方法,

    templ = template.Must(template.New("fileName").Funcs(fm).ParseFiles("fileName"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多