<!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);
您可以将其作为一个结构传递,如下所示:
layoutData := 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>