项目后台采用gin,前后端不分离,前端使用layui
报错信息如下:
error calling gt: incompatible types for comparison
template: index.html:26:15: executing "test/index.html" at <gt $item.Price 45>: error calling gt: incompatible types for comparison
错误原因:需要判断的类型和条件类型不一致
我的后台接口代码如下:
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
)
func Test(c *gin.Context) {
type Book struct {
Title string
Author string
Price float64
}
books := make([]*Book, 0)
books = append(books, &Book{Title: "《流浪地球》", Author: "刘慈欣", Price: 45.50})
books = append(books, &Book{Title: "《西游记》", Author: "吴承恩", Price: 32.00})
c.HTML(http.StatusOK, "test/index.html", gin.H{
"title": "HelloWorld",
"desc": "这是测试页面",
"books": books,
})
}
前端页面代码如下:
<!-- 如果存在同名的页面
或者视图根目录(views)下还有其他文件夹,
一定要给每一个都定义一个名字,用define定义,end结束 -->
{{define "test/index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>测试页面</title>
</head>
<body>
<h1>{{.title}}</h1>
<br />
<h5>{{.desc}}</h5>
<table>
<thead>
<td>书名</td>
<td>作者</td>
<td>售价</td>
</thead>
<tbody>
{{range $item := .books }}
<tr>
<td>{{$item.Title}}</td>
<td>{{$item.Author}}</td>
{{if gt $item.Price 45}}
<td style="color: red; font-weight: bolder">{{$item.Price}}</td>
{{else}}
<td style="color: green; font-weight: bolder">{{$item.Price}}</td>
{{end}}
</tr>
{{end}}
</tbody>
</table>
</body>
</html>
{{end}}
其中Book的Price属性是float64类型,前端使用了
{{if gt $item.Price 45}}
do something...
{{end}}
去执行if判断,报错 error calling gt: incompatible types for comparison
解决方法
将if判断语句改为
{{if gt $item.Price 45.00}}
do something...
{{end}}
同为浮点型就可以了