Solution 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 :

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}}

Problem :

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

Comments

Comment posted by jusk pikanet

this solution would need to rewrite main.go file. Is there any easier solution, just to change in my .html file? or maybe I do not know how I would implement this in my case.

Comment posted by Tiago Peczenyj

Are you sure? Check the edit

Comment posted by jusk pikanet

In the code/solution you proposed, “there is no code” is printed even before search is performed. And now also results does not show. It must be {{if .}} before range. So, it does not work…

Comment posted by Tiago Peczenyj

You can use a pointer to a struct with two fields: Found (bool) and result. If no pointer, show nothing, etc

Comment posted by jusk pikanet

I do not get it 🙁

By