<!DOCTYPE html> <html> <head> <title> Test </title> </head> <body> <div> <h2>Reply</h2> <form action="/post/{{$threadID}}" method="POST"> <input type="text" name="subject" /> <input type="text" name="name" value="Anonymous" /> <input type="text" name="message" /> <input type="submit" value="submit" /> </form> </div> <div> {{range .}} {{$threadID := .ThreadID}} <h3>{{.Subject}}</h3> <h3>{{.Name}}</h3> <div>{{.DatePosted}}</div> <div><p>{{.Text}}</p></div> <br /><br /> {{end}} </div> </body>
我有这个模板,在页面顶部有一个表单需要发送任何一个帖子的threadID(它们都是相同的,所有帖子都有一定的threadID),这显然不是工作,我唯一的另一个想法就是这样
{{range .}} {{if $threadID == nil}} $threadID := .ThreadID //build the form same as above {{end}} <h3>{{.Subject}}</h3> <h3>{{.Name}}</h3> <div>{{.DatePosted}}</div> <div><p>{{.Text}}</p></div> <br /><br /> {{end}}
如果上述任何一个不清楚,这是Post结构和方法.
type Post struct { threadID int subject string name string text string date_posted string } func (p *Post) ThreadID() int { return p.threadID } func (p *Post) Subject() string { return p.subject } func (p *Post) Name() string { return p.name } func (p *Post) Text() string { return p.text } func (p *Post) DatePosted() string { return p.date_posted }
并且发送到模板的帖子片的来源
threadID := r.URL.Path[len("/reply/"):] replies,err := i.db.Query("SELECT * FROM latest_threads where thread_id="+threadID);
您可以将它作为一个结构传递,如下所示:
原文链接:https://www.f2er.com/go/242048.htmllayoutData := struct { ThreadID int Posts []Post } { ThreadID: threadID,Posts: Posts,}
那么这样的事情就行了起来
<!DOCTYPE html> <html> <head> <title> Test </title> </head> <body> <div> <h2>Reply</h2> <form action="/post/{{ .ThreadID }}" method="POST"> <input type="text" name="subject" /> <input type="text" name="name" value="Anonymous" /> <input type="text" name="message" /> <input type="submit" value="submit" /> </form> </div> <div> {{range $post := .Posts}} <h3>{{ $post.Subject}}</h3> <h3>{{$post.Name}}</h3> <div>{{$post.DatePosted}}</div> <div><p>{{$post.Text}}</p></div> <br /><br /> {{end}} </div> </body>