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

时间:2019-06-10 15:48:45

标签: go go-templates

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

//                                ┌ enable MULTILINE option
//                                |  ┌ match start of the line
//                                |  | ┌ ensure that there is PERS|TASK PERS 
//                                ↓  ↓ ↓ after it (after start of the line)
newContent = content.replaceAll("(?m)^(?=PERS|TASK PERS)", "!");
//                                                          ↑
//                                    we can use only ! because `PERS|TASK PERS` 
//                                    will not be part of match so it will 
//                                              not be replaced

但这不起作用,并且出现此错误:

    {{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}}

那我该如何解决呢?

1 个答案:

答案 0 :(得分:7)

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

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

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