Go cannot evaluate field when using range to build from template

I have a Files fragment of the File structure in my Go program to save the name and size of the files. I created a template, see below:

 type File struct { FileName string FileSize int64 } var Files []File const tmpl = ` {{range .Files}} file {{.}} {{end}} ` t := template.Must(template.New("html").Parse(tmplhtml)) err = t.Execute(os.Stdout, Files) if err != nil { panic(err) } 

Of course I got a panic saying:

cannot evaluate the Files field in type [] main.File

Not sure how to display file names and sizes correctly with range in a template.

+2
source share
1 answer

The initial value of your pipeline (dot) is the value you pass to Template.Execute() , which in your case is Files which is of type []File .

Thus, at run time, the dot . equal to []File . This slice does not have a field or method named Files , which means .Files in your template.

What you have to do, just use . which refers to your fragment:

 const tmpl = ` {{range .}} file {{.}} {{end}} ` 

And it's all. Testing:

 var Files []File = []File{ File{"data.txt", 123}, File{"prog.txt", 5678}, } t := template.Must(template.New("html").Parse(tmpl)) err := t.Execute(os.Stdout, Files) 

Conclusion (try on the Go Playground ):

 file {data.txt 123} file {prog.txt 5678} 
+5
source

Source: https://habr.com/ru/post/1266438/


All Articles