【问题标题】:Golang function 'can't evaluate field in type string'Golang函数'无法评估字符串类型中的字段'
【发布时间】:2019-01-12 22:53:23
【问题描述】:

我有一个 Item 类型的结构,其中包含 ItemFields,它是字符串类型的切片。我想有条件地打印 ItemFields 中的每个字符串,它是带有锚标记的超链接。为此,我使用了一个 IsHyperlink 函数来检查切片中的每个字符串是应该包含在锚标记中还是简单地打印出来。

type Item struct {
  ItemFields []string
}

我正在像这样在 page.html 中遍历 ItemFields。

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

但是,当我运行应用程序时 IsHyperlink 报告它“无法评估字符串类型中的字段 IsHyperlink。

如何更改我的 go 代码以成功地将超链接包装在锚标记中?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    该上下文中的值. 是一个字符串,而不是Item。使用变量来引用项目:

    {{range $item := .Items}}
      <tr>
        <td>
          {{range .ItemFields}}
            {{if $item.IsHyperlink .}}
              <a href="{{.}}">{{.}}</a>
            {{else}}
              {{.}}
            {{end}}
          {{end}}
        </td>
      </tr>
    {{end}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2022-08-16
      • 2018-10-03
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多