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

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

问题描述:

In a go template, I'd like to get the last message in a loop, to be used outside the loop:

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

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


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

But this does not work and I get this error:

 undefined variable "$lastMsg"

I have also tried {{.lastMsg := $m}} but then I get:

 unexpected ":=" in operand

So how can I fix this?

You need to declare the lastMsg variable outside the range loop in order to use it outside the loop

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

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