如何在Golang中将列表传递给模板?

huangapple go评论84阅读模式
英文:

How can i pass list to template at Golang

问题

我想将以下代码修改为在模板中列出所有的名字:

rows := db.Query("SELECT * FROM names")
var names []string

for rows.Next() {
    var name string
    rows.Scan(&name)
    names = append(names, name)
}

t.Execute(w, names)

然后在模板中使用以下代码:

{{range .}}
{{.}}
{{end}}

这样就可以按照你的需求在模板中列出所有的名字了。

英文:

I want to use a query which looks like

rows:= db.Query("SELECT * FROM names")

var name string

for rows.Next() {
    rows.Scan(&name)
}

//There should be a map

t.Execute(w,p)

I want to shape up this to list all names in template like

{{range .name}}
{{.}}
{{end}}

How can i exactly do that?

答案1

得分: 0

// 这样做可以吗?

rows, err := db.Query("SELECT name FROM names")
if err != nil {
    // 处理错误
}

names := make([]string, 0)

for rows.Next() {
    var name string

    err := rows.Scan(&name)
    if err != nil {
        // 处理错误
        continue
    }

    names = append(names, name)
}

t := template.New("index")
t, _ = t.Parse(`{{range .}}{{.}} {{end}}`)
t.Execute(w, names)

注意事项

  • 通常应避免在 SQL 查询中使用 *,以明确选择了哪些字段
  • 如果数据库表中的任何字段可能为 NULL,则使用 sql.NullBoolsql.NullFloat64sql.NullInt64sql.NullString 来避免可能的错误

可能的输出

Bob Jim David Henry Jerry

英文:

Something Like This?

rows, err := db.Query("SELECT name FROM names")
if err != nil {
	// Handle error
}

names := make([]string, 0)

for rows.Next() {
	var name string

	err := rows.Scan(&name)
	if err != nil {
		// Handle error
		continue
	}

	names = append(names, name)
}

t := template.New("index")
t, _ = t.Parse(`{{range .}}{{.}} {{end}}`)
t.Execute(w, names)

Things to Note

  • You should generally avoid using * in your sql queries to make it clear what fields are being selected
  • If any fields in your database table can be NULL, then use sql.NullBool, sql.NullFloat64, sql.NullInt64 or sql.NullString to avoid possible errors

Possible Output

Bob Jim David Henry Jerry 

huangapple
  • 本文由 发表于 2017年6月9日 00:28:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/44441091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定