go:php:templating:go_html_template_range
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| go:php:templating:go_html_template_range [2026/01/12 22:47] – created phong2018 | go:php:templating:go_html_template_range [2026/01/12 22:50] (current) – removed phong2018 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ====== php: | ||
| - | [[php: | ||
| - | |||
| - | Note: html/ | ||
| - | |||
| - | ===== What it is ===== | ||
| - | |||
| - | In Go html/ | ||
| - | |||
| - | {{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{" | ||
| - | |||
| - | 2) Index + item | ||
| - | |||
| - | {{range $i, $item := .}} | ||
| - | < | ||
| - | {{end}} | ||
| - | |||
| - | |||
| - | 3) Loop over a slice of structs | ||
| - | |||
| - | Assume your data is []User: | ||
| - | |||
| - | {{range .}} | ||
| - | < | ||
| - | {{end}} | ||
| - | |||
| - | |||
| - | 4) Empty list handling (else) | ||
| - | |||
| - | {{range .}} | ||
| - | < | ||
| - | {{else}} | ||
| - | < | ||
| - | {{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 / | ||
| - | |||
| - | action / | ||
| - | |||
| - | range /reɪndʒ/: lặp / duyệt qua | ||
| - | |||
| - | slice /slaɪs/: mảng động trong Go (danh sách thay đổi độ dài) | ||
| - | |||
| - | context / | ||
go/php/templating/go_html_template_range.1768258067.txt.gz · Last modified: by phong2018
