duanguan5922 2019-06-10 15:48
浏览 9
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • douyakan8924 2019-06-10 17:33
    关注

    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}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?