'GoLang html template if condition

I made a web app in Go which search for a query in a mysql database. Everything works fine, but I do not know how to obtain following: if there is no result in database print e.g. "there is no product". Currently code does not print anything in case if there is no data.

My index.html file:

<!DOCTYPE html>
<html> 
<body>

<h2>Select Query</h2>

<form action="/database" method="POST">
  <label for="product">Product Name:</label><br>
  <input type="text" id="productID" name="productName" <br>
  <input type="submit" value="Search">
</form>

{{if .}}
  <ul>
  {{range .}}
    <li>Name: {{.Name}}</li>
    <li>Price: ${{.Price}}</li>
    <br>
  {{end}}
{{end}}

</body>
</html>

I tried to add {{else}} condition, but in this case "there is no product" is printed even before query search or when page is loaded.

{{if .}}
  <ul>
  {{range .}}
    <li>Name: {{.Name}}</li>
    <li>Price: ${{.Price}}</li>
    <br>
  {{end}}

{{else}}
        <li>there is no product</li>
{{end}}

Can you help me please?

TIA



Solution 1:[1]

You can use range with else

Check on this example (you can easily adapt to your code)

{{range $item := .SearchData }}
    Here we are {{ $item }} 
{{ else }}
    Sorry. No matching results found
{{ end }}

https://go.dev/play/p/7xJ1LXL2u09

Or in your case

  <ul>
  {{range .}}
    <li>Name: {{.Name}}</li>
    <li>Price: ${{.Price}}</li>
    <br>
  {{else}}
    <li>there is no product</li>
  {{end}}
  </ul>

Solution 2:[2]

When scanning from the database, you can use sql.NullString to save your values, and then in your template you can check if the data is valid, and if it is, access its value.

type Response struct {
Name     sql.NullString
Price        sql.NullInt64
}

HTML

<h2>Select Query</h2>

{{if .Name.Valid}}
  <ul>
  {{range .}}
    <li>Name: {{.Name.String}}</li>
    <li>Price: ${{.Price.String}}</li>
    <br>
  {{end}}
{{else}}
<li>there is no product</li>
{{end}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dan