gpt4 book ai didi

Go:使用模板在数组中显示数组

转载 作者:数据小太阳 更新时间:2023-10-29 03:07:25 25 4
gpt4 key购买 nike

我如何像这样在 Go 模板中插入变量 - 我在 HTML 中有这段代码:

{{define "homepage"}}
<html>
<form action="/home/delete" method="POST">
{{with .Posts}}
{{range .}}
<p id="twt">{{ range $i := .Status}}{{$i}}<br><br></p>
<button type="submit" id="xbutton" name="xdel" value="{{.Tweetid}}">Delete</button>
{{end}}
{{end}}
{{end}}
</form>
</html>
{{end}}

Go 中的代码:

type User struct {
Userid int64
Username string
Password string
Posts []*Post
}

type Post struct {
Tweetid int
Username string
Status []string
}

func deletehandler(w http.ResponseWriter, r *http.Request) {
currentuser = getUserName(r)
postvalue = r.PostFormValue("xdel")
DeleteTweet()
if currentuser != "" {
as := Post{Username: currentuser, Status: ReadStatus(), Tweetid: ReadStatusId()}
person := User{Username: currentuser, Posts: []*Post{&as}}
t := template.Must(template.New("tele").ParseFiles("layout/home.html"))
if err := t.ExecuteTemplate(w, "homepage", person); err != nil {
panic(err)
}
} else {
http.Redirect(w, r, "/", 302)
}
}

//getting the .Tweetid
func ReadStatusId() (res int) {
//some code to open and access the sql database
rows, _ := db.Query("Select id from posts where tweet = ?", AddTweet)
some code for error handling
defer rows.Close()

var status string
for rows.Next() {
err := rows.Scan(&status)
if err != nil {
fmt.Println(err)
}
fmt.Printf("this %s", status)
}
return
}

func main() {
(//code for other handlers..)
router.HandleFunc("/home/delete", deletehandler).Methods("POST")
}

但是,我得到的错误信息是

can't evaluate field Tweetid in type string

如何解决此问题并允许在值字符串中读取 .Tweetid?如果这有帮助,我引用了我使用模板的方式:http://jan.newmarch.name/go/template/chapter-template.html

最佳答案

尝试更改模板:

{{range $p := .Posts}} 
<p id="twt">{{ range $i := .Status}}{{$i}}<br><br></p>
<button type="submit" id="xbutton" name="xdel" value="{{$p.Tweetid}}">Delete</button>
{{end}}
{{end}}

{{ range $i := ... }} 中使用 {{.Tweetid}} 将引用 {{$i.Tweetid} } 添加 range $p := .Posts}} 并使用 {{$p.Tweetid}} 明确引用它会解决问题

关于Go:使用模板在数组中显示数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25367310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com