This is an old revision of the document!
Table of Contents
go:templating:go_html_template_range
Go html/template (range loop)
Note: html/template is a Go (Golang) standard library, not PHP. But 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 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
<li>{{.}}</li>
If you pass []string{“a”, “b”}, you’ll get two <li> items.
2) Index + item
<div>{{$i}} - {{$item}}</div>
3) Loop over a slice of structs
Assume your data is []User:
<p>Name: {{.Name}} | Email: {{.Email}}</p>
4) Empty list handling (else)
<li>{{.}}</li>
<li>No items</li>
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)
