[SOLVED] {{ $i := $i+1 }}

Good afternoon. How in the cycle do I increase the value of the variable by 1?
In PHP, it would be like this

$i = $i + 1

There is a problem with scoping (see Scratch.Add), but to increment that variable I believe you need to create a new variable, i.e.:

$i := $i + 1
1 Like

It is not work

My code is

{{ $slug := .URL }}
{{ $i := 0 }}
{{ range first 3 (where .Site.RegularPages "Section" "blog") }}
{{ if ne .URL $slug }}
{{ $i := $i + 1 }}
{{ $i }}
					
{{ end }}
{{ end }}

As I said, there are scoping issues, and in this case you need to use $.Scratch.Add.

See https://github.com/golang/go/issues/10608

1 Like

Thanks. My result code is

{{ $slug := .URL }}
{{ .Scratch.Add "i" 0 }}
{{ range first 3 (where .Site.RegularPages "Section" "blog") }}
{{ $k := .Scratch.Get "i" }}
{{ if lt $k 2 }}
{{ if and ((ne .URL $slug) (lt $k 2) ) }}
{{ .Scratch.Add "i" 1 }}
					
{{ .Title }}

{{ end }}
{{ end }}
{{ end }}
3 Likes