Golang function 'can't evaluate field in type string'
Asked Answered
U

1

5

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?

Unessential answered 12/1, 2019 at 22:53 Comment(0)
P
7

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}}
Parcenary answered 12/1, 2019 at 22:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.