douzhiba6873 2019-01-12 22:53
浏览 40
已采纳

Golang函数“无法评估字符串类型的字段”

I have a struct of type Item that contains ItemFields which is a slice of type string. I would like to conditionally print each string in ItemFields that is a hyperlink with an anchor tag. To do so, I am using a function, IsHyperlink, to check whether each string in the slice should be wrapped in an anchor tag or simply printed out.

type Item struct {
  ItemFields []string
}

I am looping through ItemFields in my page.html like this.

{{range .Items}}
  <ul>
    <li>
      {{range .ItemFields}}
        {{if .IsHyperlink .}}
          <a href="{{.}}">{{.}}</a>
        {{else}}
          {{.}}
        {{end}}
      {{end}}
    </li>
  </ul>
{{end}}

However, when I run the application IsHyperlink is reporting that it 'cant evaluate field IsHyperlink in type string.

How can I change my go code to successfully wrap the hyperlinks in anchor tags?

  • 写回答

1条回答 默认 最新

  • dongliyan7318 2019-01-12 22:57
    关注

    The value . in that context is a string, not the Item. Use a variable to refer to the item:

    {{range $item := .Items}}
      <tr>
        <td>
          {{range .ItemFields}}
            {{if $item.IsHyperlink .}}
              <a href="{{.}}">{{.}}</a>
            {{else}}
              {{.}}
            {{end}}
          {{end}}
        </td>
      </tr>
    {{end}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)