2016-04-14 20:22
浏览 72

GO HTML /模板:测试两个点变量是否相等

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:

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

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条回答 默认 最新

  • drqj8605
    drqj8605 2016-04-14 20:28

    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.

    点赞 评论