【问题标题】:How to use template variable outside a loop?如何在循环外使用模板变量?
【发布时间】:2019-06-10 15:48:45
【问题描述】:

在 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

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

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    你需要在 range 循环外声明 lastMsg 变量才能在循环外使用它

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

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多