owl-blogs/renderer.go

118 lines
2.4 KiB
Go
Raw Normal View History

2022-08-03 14:55:48 +00:00
package owl
2022-07-21 17:02:37 +00:00
import (
"bytes"
_ "embed"
"html/template"
)
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-08-18 19:06:01 +00:00
func renderEmbedTemplate(templateFile string, data interface{}) (string, error) {
templateStr, err := embed_files.ReadFile(templateFile)
if err != nil {
return "", err
}
return renderTemplateStr(templateStr, data)
}
func renderTemplateStr(templateStr []byte, data interface{}) (string, error) {
t, err := template.New("_").Parse(string(templateStr))
if err != nil {
return "", err
}
var html bytes.Buffer
err = t.Execute(&html, data)
if err != nil {
return "", err
}
return html.String(), nil
}
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()
2022-08-18 19:06:01 +00:00
postHtml, err := renderEmbedTemplate("embed/post.html", PostRenderData{
Title: post.Title(),
Post: template.HTML(buf.String()),
})
if err != nil {
return "", err
}
data := PageContent{
Title: post.Title(),
2022-08-18 19:06:01 +00:00
Content: template.HTML(postHtml),
}
2022-08-05 20:04:03 +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 := ""
2022-08-17 19:57:55 +00:00
for _, post := range posts {
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()
2022-08-18 19:06:01 +00:00
userHtml, err := renderEmbedTemplate("embed/user-list.html", users)
2022-07-24 18:29:31 +00:00
if err != nil {
return "", err
}
data := PageContent{
Title: "Index",
2022-08-18 19:06:01 +00:00
Content: template.HTML(userHtml),
2022-07-24 18:29:31 +00:00
}
2022-08-18 19:06:01 +00:00
return renderTemplateStr([]byte(baseTemplate), data)
2022-07-24 18:29:31 +00:00
}