I'm trying to build a web forum kind of like Reddit. There are top level posts with replies and the replies can have replies and so on.
A board looks like this:
var board map[string]*Post
and a Post
:
type Post struct {
Title string
Body string
ID string
PostNum int
Replies []*Post
}
How would I use a template to range through the nested Replies
slices (keeping in mind that each *Post
contains a Replies
slice that contains *Posts
that contains Replies
and so on)?
What I have so far:
<div id="posts">
{{ .Title }}
{{ .Body }}
<ul>
{{ range $key, $value := .Replies }}
<li class="post">
<div class="postHead">
<div class="postTitle"><b>{{ $value.ID }}</b></div>
</div>
<div class="postBody">{{ $value.PostNum }}</div>
</li>
<ul>
{{ range $key, $value := $value.Replies }}
<li class="post">
<div class="postHead">
<div class="postTitle"><b>{{ $value.ID }}</b></div>
</div>
<div class="postBody">{{ $value.PostNum }}</div>
</li>
{{ end }}
</ul>
{{ end }}
</ul>
</div>
This only allows me to range through two levels of replies (and as you can see uses duplicate code), I need to be able to range through an arbitrary number of levels of Replies
.