Home >Backend Development >Golang >Do Go Template Range Loop Variables Reset on Each Iteration?

Do Go Template Range Loop Variables Reset on Each Iteration?

DDD
DDDOriginal
2024-12-21 02:20:10996browse

Do Go Template Range Loop Variables Reset on Each Iteration?

Variables in Go Template Range Loops: Are They Reset on Iteration?

In Go templates, variables declared outside a range loop are not reset on each iteration. However, an issue arises when assigning a new value to a variable within the loop.

Consider the following code:

{{ $prevDate := "" }}
{{ range $post := .Posts }}
    {{ if ne $prevDate $post.Date }}
        <div>

The intent is to compare the $prevDate to the current post's date to determine if the post occurred on the same day. However, $prevDate seems to be reset to an empty string at the start of each loop iteration.

The reason for this behavior is that the variable $prevDate is redeclared within the loop. This creates a new variable that is only in scope within the current iteration. The original $prevDate variable remains unchanged outside the loop.

To resolve this issue, there are two possible solutions:

Solution #1: Using a Registered Function

You can register a custom function that takes the current index and returns the previous post's date:

func PrevDate(i int) string {
    if i == 0 {
        return ""
    }
    return posts[i-1].Date
}

Then, in your template:

{{range $index, $post := .Posts}}
    {{$prevDate := PrevDate $index}}
    ...
{{end}}

Solution #2: Using a Method of Posts

Alternatively, you can add a method to your Posts type:

func (p *Posts) PrevDate(i int) string {
    if i == 0 {
        return ""
    }
    return (*p)[i-1].Date
}

In your template:

{{range $index, $post := .Posts}}
    {{$prevDate := $.Posts.PrevDate $index}}
    ...
{{end}}

The above is the detailed content of Do Go Template Range Loop Variables Reset on Each Iteration?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn