====== go:templating:go_html_template_range ====== Go html/template (range loop) Note: html/template is a Go (Golang) standard library. The idea of “looping in templates” is similar to PHP templating engines (Blade/Twig). ===== What it is ===== In Go html/template, the action used to loop over a slice/array/map is: {{range .}} ... {{end}} range iterates over the data (e.g., a slice) and renders the inside block once per element. . (dot) is the “current context”. Inside range, . becomes the current item. ===== What it’s for ===== Render lists in HTML: menus, table rows, cards, comments, products, etc. Iterate over a map to output key/value. Handle empty lists using else. ===== Examples ===== 1) Simple slice loop {{range .}}
  • {{.}}
  • {{end}} If you pass []string{"a", "b"}, you’ll get two
  • items. 2) Index + item {{range $i, $item := .}}
    {{$i}} - {{$item}}
    {{end}} 3) Loop over a slice of structs Assume your data is []User: {{range .}}

    Name: {{.Name}} | Email: {{.Email}}

    {{end}} 4) Empty list handling (else) {{range .}}
  • {{.}}
  • {{else}}
  • No items
  • {{end}} ===== Key points ===== The correct loop syntax is {{range .}} ... {{end}}. Inside range, . becomes the current element. You can bind variables: {{range $i, $v := .}} ... {{end}}. You can add {{else}} to handle empty collections. ===== Hard words (with IPA + Vietnamese) ===== template /ˈtɛm.plət/: mẫu giao diện / khuôn render action /ˈæk.ʃən/: hành động (cú pháp lệnh trong template) range /reɪndʒ/: lặp / duyệt qua slice /slaɪs/: mảng động trong Go (danh sách thay đổi độ dài) context /ˈkɒn.tekst/: ngữ cảnh (dữ liệu mà . đang trỏ tới)