Go html/template 索引及键

使用 index 函数获取切片或Map指定元素

语法 :

{{index $切片或map 索引值 [整数索引或字符串键]}}

示例

go 源码

package main

import (
	"html/template"
	"net/http"

	"github.com/gin-gonic/gin"
)
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		template, _ := template.ParseFiles("./templates/index.html")
		template.Execute(w, gin.H{
			"colors": []string{"red", "orange"},
			"person": map[string]string{
				"name":  "lesscode",
				"class": "一年五班",
			},
		})
	})
	http.ListenAndServe(":8080", nil)
}

html 源码

<html>
<body>
    <h3 style="color:{{index .colors 1}};">
        {{index .person "name"}}
    </h3>
</body>
</html>