GO html/template: 测试两个点变量的相等性

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

GO html/template: test equality of two dot variables

问题

我正在发送一个html/template给这个模型:

type MapModel struct {
    Networks []*NetworkMeta
    WaveKey  string
}

Networks字段由另一个类型NetworkMeta定义:

type NetworkMeta struct {
    NetworkMetaKey string
}

我使用Networks数组来生成一个html select对象:

<select name="waveKey" id="waveKey">
    {{range .Networks}}
    <option value="{{ .NetworkMetaKey}}" {{if eq .NetworkMetaKey .WaveKey }} selected="selected" {{end}}>
        {{ .NetworkMetaKey }}
    </option>
    {{end}}
</select>

这里的所有内容都可以正常工作,除了"if eq"的等式测试。该测试返回错误:"WaveKey不是*models.NetworkMeta结构类型的字段"。

据我了解,html/template的eq运算符是将一个值与另一个值(或一组值)进行比较,两个值之间用空格分隔。然而,在这种情况下,错误似乎表明对于字段,编译器忽略了空格。

有没有办法使这个等式工作?我需要编写一个自定义函数吗?

谢谢您的帮助。

英文:

I'm sending an html/template this model:

type MapModel struct {
Networks      []*NetworkMeta
WaveKey       string

}

The Networks field is defined by another type, NetworkMeta:

type NetworkMeta struct {
NetworkMetaKey string

}

I use the Networks array to produce an html select object:

            &lt;select name=&quot;waveKey&quot; id=&quot;waveKey&quot;&gt;
    {{range .Networks}}
            &lt;option value=&quot;{{ .NetworkMetaKey}}&quot; {{if eq .NetworkMetaKey .WaveKey }} selected=&quot;selected&quot; {{end}}&gt;
            {{ .NetworkMetaKey }}
            &lt;/option&gt;
    {{end}}

Everything here works except the "if eq" equality test. That test returns the error: "WaveKey is not a field of struct type *models.NetworkMeta."

As I understand the html/template eq operator, the comparison tests one value against another (or a group of values), the one separated from the rest by a space. In this case, however, the error seems to indicate that for a field, the compiler ignores the space.

Is there any way to make this equality work? Do I need to write a custom func?

Thanks for any help.

答案1

得分: 1

dot正在遍历网络切片,所以它的类型是*NetworkMeta。NetworkMeta没有任何WaveKey字段。

如果你想要访问不同作用域的值,可能需要使用自定义函数。

英文:

dot is iterating through the slice of Networks, so it is of type *NetworkMeta. NetworkMeta doesn't have any fields of WaveKey.

A custom func might be what you want since you are trying to access the values from different scopes.

huangapple
  • 本文由 发表于 2016年4月15日 04:22:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/36633256.html
匿名

发表评论

匿名网友

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

确定