Lansana Camara
Lansana Camara

Reputation: 9873

error: template: "..." is an incomplete or empty template

I'm trying to add a FuncMap to my templates, but I'm receiving the following error:

template: "foo" is an incomplete or empty template

The parsing of templates worked just fine before I used the FuncMap, so I'm not sure why it's throwing an error now.

Here is my code:

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() just returns a slice of strings that are file paths.

Anyone know what's up?

Upvotes: 71

Views: 32410

Answers (3)

Jacob
Jacob

Reputation: 2444

You can also use Template.Must method,

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

Upvotes: 0

iDuran
iDuran

Reputation: 398

I was having the same problem. I realized that

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

also works if you use it with

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

If I use

err := tpl.Execute(wr, data)

then I should specify the template name in New():

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

Upvotes: 17

jrefior
jrefior

Reputation: 4431

Make sure the argument you pass to template.New is the base name of one of the files in the list you pass to ParseFiles.

One option is

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

ParseFiles documentation:

Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files.

Upvotes: 140

Related Questions