go template 模板使用
在beego中預設開啟自動渲染,view目錄中的模板檔案會自動解析;使用者無需手動的呼叫渲染輸出模板,beego 會自動的在呼叫完相應的 method 方法之後呼叫 Render 函式;而模板中的資料是通過在 Controller 中 this.Data 獲取的,所以如果你想在模板中獲取內容 {{.Content}} ,那麼你需要在 Controller 中如下設定:
this.Data["key"] = interface{}
即“key”對應的資料可以設定成任何資料結構。
在最近的專案中需要解析的資料後端程式碼如下:
type k8sNode struct { Name string Ip string Status string Cpu int64 Memory int64 JoinDate string System string DockerVersion string Pods []string } func (c *BaseController) GetNode() { nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{}) if err != nil { fmt.Println("err") } nodeInformations :=[]k8sNode{} for _,node := range nodes.Items{ cpu,_ := node.Status.Allocatable.Cpu().AsInt64() memory,_ := node.Status.Allocatable.Memory().AsInt64() memory = memory / 1024 / 1024 / 1024 nodeInformation := k8sNode{ Name: node.Name, Ip: node.Status.Addresses[0].Address, Status: string(node.Status.Conditions[len(node.Status.Conditions)-1].Type), Cpu: cpu, Memory: memory, JoinDate: node.CreationTimestamp.Format("2006-01-02"), System: node.Status.NodeInfo.OSImage, DockerVersion: node.Status.NodeInfo.ContainerRuntimeVersion, } nodeInformations = append(nodeInformations,nodeInformation) } c.Data["k8snode"] = nodeInformations }
前端模板檔案程式碼片段如下:
{{ range $node := .k8snode }} <div class="col-lg-3 col-xs-6"> <!-- small box --> <div class="small-box bg-aqua"> <div class="inner"> <h4>{{ $node.Name }}</h4> <hr > <p class="node-p">HostIp:{{ $node.Ip }}</p> <p class="node-p">狀態:{{ $node.Status }}</p> <p class="node-p">cpu:{{ $node.Cpu }}核</p> <p class="node-p">記憶體:{{ $node.Memory }}G</p> <p class="node-p">建立:{{ $node.JoinDate }}</p> <p class="node-p">系統:{{ $node.System }}</p> <p class="node-p">docker:{{ $node.DockerVersion }}</p> <p class="node-p">pods:cloud-erp,cloud-zipkin</p> </div> <div class="icon" > <i class="ion ion-clipboard"></i> </div> <a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a> </div> </div> {{ end }}
==================================================================
有關golang的template的所有基本語法,請參照goLang的官方文件,地址:ofollow,noindex">https://golang.org/doc/ ,本篇文章如果有錯誤處還望批評指正。