首页 > 解决方案 > Golang函数'无法评估字符串类型中的字段'

问题描述

我有一个 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 代码以成功地将超链接包装在锚标记中?

标签: gogo-templates

解决方案


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

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

推荐阅读