登录
首页 >  Golang >  Go问答

使用模型数组中的选项渲染 SelectTag()

来源:stackoverflow

时间:2024-03-29 21:45:32 380浏览 收藏

本篇文章给大家分享《使用模型数组中的选项渲染 SelectTag()》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我的应用程序中有一个 user 模型和 app 模型。 appuser 模型具有 belongs_to 关系。

在模板 apps/new.plush.html 中,我需要将用户列表呈现为下拉选择。我已经在 user 模型中实现了 forms.selectable 接口,如下所示 -

func (a *user) selectlabel() string {
    return a.name
}

func (a *user) selectvalue() interface{} {
    return a.id
}

apps.go 中的 new() 操作如下所示 -

func (v appsresource) new(c buffalo.context) error {
    tx, ok := c.value("tx").(*pop.connection)
    if !ok {
        return fmt.errorf("no transaction found")
    }

    users := &models.users{}
    if aterr := tx.all(users); aterr != nil {
        return c.error(http.statusnotfound, aterr)
    }

    c.set("users", users)
    c.set("app", &models.app{})

    return c.render(http.statusok, r.html("/apps/new.plush.html"))
}

现在,如何编写选择标签来呈现 users 数组中的选项?

以下不起作用 -

<%= f.SelectTag("UserID", {options: users})%>

解决方案


我从#buffalo slack频道找到了解决方案。问题在于 -

func (a *user) selectlabel() string {
    return a.name
}

func (a *user) selectvalue() interface{} {
    return a.id
}

这些不应该是指针方法。正确的版本是-

func (a User) SelectLabel() string {
    return a.Name
}

func (a User) SelectValue() interface{} {
    return a.ID
}

今天关于《使用模型数组中的选项渲染 SelectTag()》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>