Here is the Post structure and methods if any of the above is unclear.

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,
}

然后像这样的东西将工作

Then something like this will work

<!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>

这篇关于在golang html模板中访问{{range。}}作用域之外的结构变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!