-
Notifications
You must be signed in to change notification settings - Fork 11
/
render.go
55 lines (45 loc) · 1.17 KB
/
render.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"bytes"
"encoding/json"
"log"
"os"
"text/template"
)
// RenderStruct 渲染模板的数据结构
type RenderStruct struct {
Friends []*Friend `json:"friends"`
Posts []Post `json:"posts"`
}
// RenderMarkdown 将朋友信息和最近的文章渲染成Markdown格式
func RenderMarkdown(friends []*Friend, posts []Post) []byte {
markdownTemplate, err := os.ReadFile(Config.TemplatePath)
if err != nil {
log.Fatalf("Failed to read template file: %v", err)
}
tmpl, err := template.New("markdown").Parse(string(markdownTemplate))
if err != nil {
log.Fatalf("Failed to parse template: %v", err)
}
var buffer bytes.Buffer
data := RenderStruct{
Friends: friends,
Posts: posts,
}
if err := tmpl.Execute(&buffer, data); err != nil {
log.Fatalf("Failed to render template: %v", err)
}
return buffer.Bytes()
}
// RenderJson 将朋友信息和最近的文章渲染成JSON格式
func RenderJson(friends []*Friend, posts []Post) []byte {
data := RenderStruct{
Friends: friends,
Posts: posts,
}
marshal, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Fatalf("Failed to render template: %v", err)
}
return marshal
}