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

Go 如何在循环外使用模板变量?,go,go-templates,Go,Go Templates,在go模板中,我希望获得循环中的最后一条消息,在循环外使用: {{range $m := .messages}} <div>Message subject: {{$m.Subject}}</div> {{$lastMsg := $m}} {{end}} <div>The last message's subject: {{$lasMsg.Subject}}</div

在go模板中,我希望获得循环中的最后一条消息,在循环外使用:

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

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


    <div>The last message's subject: {{$lasMsg.Subject}}</div> 
我还尝试了
{{.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}}
{{$lastMsg:=''}//在循环外声明
{{range$m:=.messages}
消息主题:{{$m.subject}
{{$lastMsg=$m}}//分配值
{{end}
{{$lastMsg := ""}} // declare outside the loop
{{range $m := .messages}}      
        <div>Message subject: {{$m.Subject}}</div>

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