如何在循环外使用模板变量?

How to use template variable outside a loop?

在 go 模板中,我想获取循环中的最后一条消息,以在循环外使用:

    {{range $m := .messages}}      
            <div>Message subject: {{$m.Subject}}</div>

            {{$lastMsg := $m}}
    {{end}}


    <div>The last message's subject: {{$lasMsg.Subject}}</div> 

但这不起作用,我得到这个错误:

 undefined variable "$lastMsg"

我也试过 {{.lastMsg := $m}} 但后来我得到:

 unexpected ":=" in operand

那么我该如何解决这个问题?

您需要在范围循环外声明 lastMsg 变量,以便在循环外使用它

{{$lastMsg := ""}} // declare outside the loop
{{range $m := .messages}}      
        <div>Message subject: {{$m.Subject}}</div>

        {{$lastMsg = $m}} // assign the value 
{{end}}