owl-blogs/renderer.go

119 lines
2.3 KiB
Go
Raw Normal View History

2022-07-21 17:02:37 +00:00
package kiss
import (
"bytes"
_ "embed"
"html/template"
)
//go:embed embed/user-list.html
var userListTemplateStr string
//go:embed embed/post.html
var postTemplateStr string
type PageContent struct {
Title string
Content template.HTML
}
type PostRenderData struct {
Title string
Post template.HTML
}
2022-07-21 17:44:07 +00:00
2022-07-27 19:53:56 +00:00
func renderIntoBaseTemplate(user User, data PageContent) (string, error) {
baseTemplate, _ := user.Template()
t, err := template.New("index").Parse(baseTemplate)
if err != nil {
return "", err
}
user_config, _ := user.Config()
full_data := struct {
Title string
Content template.HTML
UserTitle string
UserSubtitle string
HeaderColor string
}{
Title: data.Title,
Content: data.Content,
UserTitle: user_config.Title,
UserSubtitle: user_config.SubTitle,
HeaderColor: user_config.HeaderColor,
}
var html bytes.Buffer
t.Execute(&html, full_data)
return html.String(), nil
}
2022-07-21 17:44:07 +00:00
func RenderPost(post Post) (string, error) {
buf, _ := post.MarkdownData()
postTemplate, _ := template.New("post").Parse(postTemplateStr)
var postHtml bytes.Buffer
err := postTemplate.Execute(&postHtml, PostRenderData{
Title: post.Title(),
Post: template.HTML(buf.String()),
})
if err != nil {
return "", err
}
data := PageContent{
Title: post.Title(),
Content: template.HTML(postHtml.String()),
}
2022-07-27 19:53:56 +00:00
return renderIntoBaseTemplate(post.user, data)
2022-07-21 17:02:37 +00:00
}
2022-07-23 15:19:47 +00:00
func RenderIndexPage(user User) (string, error) {
posts, _ := user.Posts()
2022-07-23 15:19:47 +00:00
postHtml := ""
for _, postId := range posts {
post, _ := user.GetPost(postId)
2022-07-24 13:34:52 +00:00
postHtml += "<h2><a href=\"" + post.UrlPath() + "\">" + post.Title() + "</a></h2>\n"
2022-07-23 15:19:47 +00:00
}
data := PageContent{
Title: "Index",
Content: template.HTML(postHtml),
}
2022-07-27 19:53:56 +00:00
return renderIntoBaseTemplate(user, data)
2022-07-23 15:19:47 +00:00
}
2022-07-24 18:29:31 +00:00
func RenderUserList(repo Repository) (string, error) {
baseTemplate, _ := repo.Template()
users, _ := repo.Users()
t, err := template.New("user_list").Parse(userListTemplateStr)
if err != nil {
return "", err
}
var userHtml bytes.Buffer
t.Execute(&userHtml, users)
data := PageContent{
Title: "Index",
Content: template.HTML(userHtml.String()),
}
var html bytes.Buffer
t, err = template.New("index").Parse(baseTemplate)
if err != nil {
return "", err
}
t.Execute(&html, data)
return html.String(), nil
}