sorted posts

posts
serr 2025-04-12 17:32:35 +03:00
parent 7e620f7308
commit 3c301dbefc
5 changed files with 29 additions and 17 deletions

View File

@ -17,7 +17,7 @@ type Post struct {
Link PostLink
Preview template.HTML
Data template.HTML
CreateTimestamp int64
ModTimestamp int64
}
func RenderPostPage(templates *template.Template, version int64, data template.HTML) ([]byte, error) {
@ -36,7 +36,7 @@ func RenderPostPage(templates *template.Template, version int64, data template.H
return pageData.Bytes(), nil
}
func newPost(link string, data []byte) *Post {
func newPost(link string, data []byte, modTimestamp int64) *Post {
previewBuf := make([]byte, 0, 503)
if len(data) > 500 {
@ -50,6 +50,6 @@ func newPost(link string, data []byte) *Post {
Link: PostLink(link),
Preview: template.HTML(previewBuf),
Data: template.HTML(data),
CreateTimestamp: time.Now().Unix(),
ModTimestamp: modTimestamp,
}
}

View File

@ -8,6 +8,7 @@ import (
"main/tools"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
@ -41,7 +42,8 @@ func LoadPosts(dir string) (Posts, error) {
html := tools.MdToHTML(md)
link := fmt.Sprintf("/%s/", strings.TrimSuffix(filepath.Base(path), ".md"))
posts[PostLink(link)] = newPost(link, html)
modTimestamp := f.ModTime().Unix()
posts[PostLink(link)] = newPost(link, html, modTimestamp)
}
return nil
})
@ -56,10 +58,20 @@ func LoadPosts(dir string) (Posts, error) {
func (p *Posts) RenderPostsPage(templates *template.Template, version int64) ([]byte, error) {
var pageData bytes.Buffer
postsSlice := make([]*Post, 0, len(*p))
for _, post := range *p {
postsSlice = append(postsSlice, post)
}
// Сортирую по ModTimestamp (новые сначала)
sort.Slice(postsSlice, func(i, j int) bool {
return postsSlice[i].ModTimestamp > postsSlice[j].ModTimestamp
})
context := map[string]any{
"version": version,
"renderingTimestamp": time.Now().Unix(),
"posts": p,
"posts": postsSlice,
}
if err := templates.ExecuteTemplate(&pageData, PostsPageTmplName, context); err != nil {

View File

@ -5,10 +5,7 @@
</div>
<div>
<p>
and also you can subscribe to my Telegram channel with pictures!
</p>
<p>
<a href="https://t.me/lolistack" target="_blank">digital countryside</a>
and also you can subscribe to my <a href="https://t.me/lolistack" target="_blank">telegram channel </a> with pictures!
</p>
</div>
<div>

View File

@ -5,7 +5,7 @@
{{ template "header" . }}
<main>
{{ range $key, $post := .posts }}
{{ range $ind, $post := .posts }}
<div class="post">
<p>
{{ $post.Preview }}
@ -14,7 +14,7 @@
<a href="{{ $post.Link }}">read more</a>
</p>
<p>
<code>created at: {{ $post.CreateTimestamp }}</code>
<code>changed at: {{ $post.ModTimestamp }}</code>
</p>
</div>
{{ end }}

3
posts/test2.md Normal file
View File

@ -0,0 +1,3 @@
# TEST 2
123