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
Release: 2024-12-21 02:20:10
Original
883 people have browsed it

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>
Copy after login

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
}
Copy after login

Then, in your template:

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

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
}
Copy after login

In your template:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template