Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go template: calling method on $variable in template

Tags:

templates

go

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.

like image 485
Elliot E Avatar asked Aug 31 '25 02:08

Elliot E


1 Answers

The Path method is on the pointer receiver:

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

The value in $path is a Path. The method Path() cannot be called on a Path because pointer receiver methods are not in the value type's method set.

There are two ways to fix the problem. The first is to declare the method with a value receiver:

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

The second way to fix the problem is to use *Path values instead of Path values. Change the map to:

var m map[string]*UpFile

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!