Go web開發判斷table裡元素的大小,並根據資料正負或大小設定不同樣式
問題描述:
比如新浪財經美股行情中心,漲跌額和漲跌幅,正數顯示紅色,負數顯示綠色
在用Go語言開發時,如何實現這樣的效果?
第一種方法:不使用js
Go語言內建了一些進行模板渲染的函式,在官方原始碼/src/text/template/funcs.go
中,專門用於GoWeb模板中的資料判斷或比較
type FuncMap map[string]interface{}
var builtins = FuncMap{
"and": and,
"call": call,
"html": HTMLEscaper,
"index": index,
"js": JSEscaper,
"len": length,
"not": not,
"or": or,
"print": fmt.Sprint,
"printf": fmt.Sprintf,
"println": fmt.Sprintln,
"urlquery": URLQueryEscaper,
// Comparisons
"eq": eq, // ==
"ge": ge, // >=
"gt": gt, // >
"le": le, // <=
"lt": lt, // <
"ne": ne, // !=
}
根據字面意思以及註釋就知道哪個是幹什麼的,比如eq
就是判斷兩個元素是否相等,lt
就是判斷a元素是否小於b元素。
在.html
檔案中的用法是
{{if gt .Percent 0.0}}
即判斷.Percent
是否大於0,如果Percent
是整數,就要寫成0,即跟0比較;如果Percent
是小數,就要寫成0.0,否則就因會型別不一致報錯。
接下來用一個完整的例子,看一下到底怎麼使用。
建立一個專案,結構如下:
. ├── main.go ├── test │ └── test.go └── view └── test.html 2 directories, 3 files
也就只有三個檔案,不過就把如何註冊處理函式,如何啟動一個伺服器,如何給前端傳遞資料,以及前端如何渲染資料都概括了。
main.go
檔案
package main
import (
"net/http"
"GoProject/test"
)
func main() {
http.HandleFunc("/", test.Test)
http.ListenAndServe(":8080", nil)
}
這裡註冊了一個處理函式test
,做具體的邏輯處理,然後啟動伺服器,監聽8080
埠
test.go
檔案
package test
import (
"fmt"
"html/template"
"net/http"
)
type Data struct {
Country string
Percent float64
}
var Datas []*Data
//初始化資料
func init() {
d1 := &Data{"賴比瑞亞", 4.50}
d2 := &Data{"蒲隆地", 3.90}
d3 := &Data{"阿富汗", 3.85}
d4 := &Data{"喀麥隆", 2.00}
d5 := &Data{"香港", 1.00}
d6 := &Data{"古巴", -0.01}
d7 := &Data{"摩爾多瓦", -0.90}
d8 := &Data{"紐埃", -1.85}
d9 := &Data{"庫克群島", -2.23}
Datas = append(Datas, d1, d2, d3, d4, d5, d6, d7, d8, d9)
}
//處理函式:handler func(ResponseWriter, *Request))
func Test(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("view/test.html")
if err != nil {
fmt.Println(err)
}
t.Execute(w, Datas)
}
首先準備一些資料,儲存在Datas
陣列中,然後傳遞給模板test.html
test.html
模板檔案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測試</title>
</head>
<body>
<div style="width: 500px;height: 300px;margin-left: 500px;margin-top: 100px;">
<table style="margin-top: 100px;width: 330px">
<h2>世界各國人口增長率</h2>
<thead style="width: 300px">
<tr style="width: 260px;">
<th style="">國家</th>
<th style="">增長率</th>
</tr>
</thead>
<tbody>
{{range .}}
<tr style="width: 260px;">
<td style="color: blue;">{{.Country}}</td>
{{if gt .Percent 0.0}}
<td style="color: red">{{.Percent}}</td>
{{else}}
<td style="color: green">{{.Percent}}</td>
{{end}}
</tr>
{{end}}
</tbody>
</table>
</div>
</body>
</html>
這裡的{{range .}}
表示遍歷後端傳遞過來的資料,.
即表示傳遞過來的所有資料t.Execute(w, Datas)
,注意要有{{end}}
結束遍歷。
{{range .}}
到{{end}}
中的{{.Country}}
和{{.Percent}}
就是每一個Data
中的兩個資料。
這裡的{{if gt .Percent 0.0}}
就是判斷增長率Percent
是否大於0,由於Percent
是float64
型別,所以要跟0.0
比較,否則會導致型別不一致,報錯。
{{if gt .Percent 0.0}}
<td style="color: red">{{.Percent}}</td>
{{else}}
<td style="color: green">{{.Percent}}</td>
{{end}}
只需一段if
語句,即完成了table表格中元素大小的判斷,然後大於0的設定紅色,小於0的設定綠色。
接下來執行main.go
,用瀏覽器訪問http://localhost:8080/,效果如下
第二種方法:使用js
使用js就稍微麻煩一些,要新增jquery
庫,程式碼也會多一些。專案結構如下,需要新增jquery
庫,並在html模板中引入js檔案,然後還要寫js程式碼。
.
├── main.go
├── static
│ ├── jquery-3.3.1.min.js
│ └── jquery.url.js
├── test
│ └── test.go
└── view
└── test.html
3 directories, 5 files
就是比剛才多了個static
資料夾,多了兩個js檔案。
首先要在main函式中註冊靜態檔案服務
在剛才的main.go
檔案中增加兩行程式碼,
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", test.Test)
http.ListenAndServe(":8080", nil)
}
也就是告訴編譯器,靜態檔案→包括js
、css
、jpeg
圖片檔案在什麼地方,這一段程式碼就是說靜態檔案在專案的根目錄下的static
資料夾下。如果沒有這一段程式碼,那麼編譯器就找不到js檔案在哪裡,因此html檔案中的js程式碼就不會被執行。
然後在test.html
中增加一些程式碼,具體如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測試</title>
<script type="text/javascript" src="../static/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="../static/jquery.url.js"></script>
<script>
function changeColor() {
$('.percent').each(function (i) {
var colorStr = '';
if ($('.percent').eq(i).html() > 0) {
colorStr = 'red';
} else {
colorStr = 'green';
}
$('.percent').eq(i).css('color', colorStr);
});
}
</script>
</head>
<body onload="changeColor()">
<div style="width: 500px;height: 300px;margin-left: 500px;margin-top: 100px;">
<table style="margin-top: 100px;width: 330px">
<h2>世界各國人口增長率</h2>
<thead style="width: 300px">
<tr style="width: 260px;">
<th style="">國家</th>
<th style="">增長率</th>
</tr>
</thead>
<tbody>
{{range .}}
<tr style="width: 260px;">
<td style="color: blue;">{{.Country}}</td>
<td class="percent" style="">
{{.Percent}}
</td>
</tr>
{{end}}
</tbody>
</table>
</div>
</body>
</html>
也就是增加了一個js函式,獲取目標元素,並判斷目標元素的大小,根據正負設定不同的樣式
<script>
function changeColor() {
$('.percent').each(function (i) {
var colorStr = '';
if ($('.percent').eq(i).html() > 0) {
colorStr = 'red';
} else {
colorStr = 'green';
}
$('.percent').eq(i).css('color', colorStr);
});
}
</script>
這裡的.Percent
是類名,根據類名查詢元素,然後一個一個判斷,如果大於0,就設定紅色樣式,如果小於0,就設定綠色樣式。
然後在<body></body>
標籤中引入js函式changeColor()
,
<body onload="changeColor()">
刪除table中的那幾行判斷語句,改為這樣:
<td class="percent" style="">{{.Percent}}</td>
這樣就OK了,也很簡單。