Go html/template 循环语句

range 迭代

语法 :

{{range $索引或键名称, $值 := .data}}
    // do ...
{{end}}

示例

package main

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

type Person struct {
	Name string
	Age  int
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		persons := []Person{
			{Name: "小明", Age: 18},
			{Name: "小李", Age: 20},
		}
		t := template.New("index.html")
		t, err := t.ParseFiles("./templates/index.html")
		if err != nil {
			fmt.Printf("err: %v\n", err)
		}
		t.Execute(w, map[string]any{"persons": persons})
	})
	http.ListenAndServe(":8080", nil)
}

html 源码

<html>
<body>
    <ul>
        {{range $idx, $person := .persons}}
        <li>{{$person.Name}} {{$person.Age}}</li>
        {{end}}
    </ul>
</body>
</html>