繁体   English   中英

错误:模板:“...”是一个不完整或空的模板

[英]error: template: "..." is an incomplete or empty template

我正在尝试将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()只返回作为文件路径的字符串片段。

有谁知道怎么回事?

确保传递给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文档

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

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

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

您还可以使用 Template.Must 方法,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM