小编grh*_*rhn的帖子

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

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

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

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


    <div>The last message's subject: {{$lasMsg.Subject}}</div> 
Run Code Online (Sandbox Code Playgroud)

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

 undefined variable "$lastMsg"
Run Code Online (Sandbox Code Playgroud)

我也尝试过,{{.lastMsg := $m}}但随后得到:

 unexpected ":=" in operand
Run Code Online (Sandbox Code Playgroud)

那么我该如何解决呢?

go go-templates

3
推荐指数
1
解决办法
77
查看次数

在返回参数中不能使用 nil 作为类型 model.Article

我有这个函数,它应该查询数据库并返回一个articleif ,如果没有找到文章,则返回nil:

func GetArticleBySlug(slug string) (model.Article, error) {
    var err error
    var article model.Article
    err = database.SQL.Get(&article, "SELECT * FROM article WHERE slug=? LIMIT 1", slug)
    if err != nil {
        log.Println(err)
        return nil, err //<- Problem here
    }
    return article, nil
}
Run Code Online (Sandbox Code Playgroud)

包中Article定义的结构体在哪里model

但我收到此错误:

cannot use nil as type model.Article in return argument
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

go

-2
推荐指数
1
解决办法
1548
查看次数

标签 统计

go ×2

go-templates ×1