User Tools

Site Tools


go:php:templating:go_html_template_range

This is an old revision of the document!


php:templating:go_html_template_range

PHPTemplating → 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:

rangeend

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 rangeend.

Inside range, . becomes the current element.

You can bind variables: range_i_vend.

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.1768258067.txt.gz · Last modified: by phong2018