转到模板:在模板中的$ variable上调用方法

For some reason my template is not working, and I can't tell why. The value of . is a map[string]UpFile where UpFile is a struct with the method Path() which takes no arguments. Here is the relevant part of the template:

{{ range $key, $value := . }}
<a href="{{ $value.Path }}">{{ $key }}</a>
{{ end }}

The template works without the call to Path() on the variable $value. I've also tested the call to Path when the value of . was UpFile and it worked. The go doc on templates says calls to methods on variables is fine. The template compiles and is served however nothing in the range is outputted. When I omit the call to Path() I get a string of characters. Thanks for taking a look.

edit: Using a field from UpFile rather than the Path method provides expected output. Still don't understand why calling Path doesn't work.

If the Path method is on the pointer receiver

func (f *UpFile) Path() string { return f.path }

then change the map values to pointers

var m map[string]*UpFile

Because map values are not addressable, it's not possible to call a *UpFile method on an UpFile map value.

Another option is to change the Path method to use the non-pointer receiver type UpFile.

Just omit the parentheses and it should be fine. Example:

{{ range $key, $value := . }}
  <a href="{{ .Path }}">{{ $key }}</a>
{{ end }}