User Tools

Site Tools


go:php:templating:go_html_template_range

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
go:php:templating:go_html_template_range [2026/01/12 22:48] phong2018go:php:templating:go_html_template_range [2026/01/12 22:50] (current) – removed phong2018
Line 1: Line 1:
-====== php: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 .}} ... {{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 .}} 
-  <li>{{.}}</li> 
-{{end}} 
- 
- 
-If you pass []string{"a", "b"}, you’ll get two <li> items. 
- 
-2) Index + item 
- 
-{{range $i, $item := .}} 
-  <div>{{$i}} - {{$item}}</div> 
-{{end}} 
- 
- 
-3) Loop over a slice of structs 
- 
-Assume your data is []User: 
- 
-{{range .}} 
-  <p>Name: {{.Name}} | Email: {{.Email}}</p> 
-{{end}} 
- 
- 
-4) Empty list handling (else) 
- 
-{{range .}} 
-  <li>{{.}}</li> 
-{{else}} 
-  <li>No items</li> 
-{{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) 
go/php/templating/go_html_template_range.1768258130.txt.gz · Last modified: by phong2018