Go模板:在模板中调用$variable的方法

huangapple go评论81阅读模式
英文:

Go template: calling method on $variable in template

问题

由于某种原因,我的模板不起作用,我无法确定原因。.的值是一个map[string]UpFile,其中UpFile是一个具有Path()方法的结构体,该方法不接受任何参数。以下是模板的相关部分:

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

在变量$value上调用Path()方法之前,模板可以正常工作。我还测试了当.的值为UpFile时调用Path的情况,它也可以正常工作。模板文档中说对变量的方法调用是可以的。模板编译并提供服务,但是在范围内没有输出任何内容。当我省略对Path()的调用时,我得到一串字符。感谢您的帮助。

编辑:使用UpFile的字段而不是Path方法提供了预期的输出。仍然不明白为什么调用Path不起作用。

英文:

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.

答案1

得分: 4

Path方法是在指针接收器上定义的:

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

$path中的值是一个Path。不能在Path上调用Path()方法,因为指针接收器方法不在值类型的方法集中。

有两种方法可以解决这个问题。第一种方法是使用值接收器声明方法:

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

第二种方法是使用*Path值而不是Path值。将映射更改为:

var m map[string]*UpFile
英文:

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

答案2

得分: -2

只需省略括号,就可以了。示例:

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

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

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

huangapple
  • 本文由 发表于 2016年3月4日 12:05:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/35787799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定