Skip to content

Commit ec7a35b

Browse files
TIL-7 Tags into pages
Signed-off-by: Chris Cummer <[email protected]>
1 parent 91ac7f6 commit ec7a35b

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

main.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,23 @@ func main() {
112112

113113
func buildContent() {
114114
pages := loadPages()
115+
buildContentPages(pages)
115116
tagMap := buildTagPages(pages)
116117

117118
buildIndexPage(pages, tagMap)
118119
}
119120

121+
// buildContentPages loops through all the pages and tells them to save themselves
122+
// to disk. This process writes any auto-generated content into the pages
123+
func buildContentPages(pages []*pages.Page) {
124+
for _, page := range pages {
125+
if page.IsContentPage() {
126+
page.AppendTagsToContent()
127+
page.Save()
128+
}
129+
}
130+
}
131+
120132
// buildIndexPage creates the main index.md page that is the root of the site
121133
func buildIndexPage(pageSet []*pages.Page, tagMap *pages.TagMap) {
122134
src.Info(statusIdxBuild)

pages/page.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"io/ioutil"
66
"os/exec"
77
"path/filepath"
8+
"regexp"
89
"strings"
910
"time"
1011

@@ -50,6 +51,47 @@ func NewPage(title string, targetDir string) *Page {
5051
return page
5152
}
5253

54+
// AppendTagsToContent programatically modifies the page content to save auto-included
55+
// content like the tag list
56+
func (page *Page) AppendTagsToContent() bool {
57+
if len(page.Tags()) == 0 {
58+
return true
59+
}
60+
61+
tagLinks := []string{}
62+
for _, tag := range page.Tags() {
63+
if tag.Link() != "" {
64+
tagLinks = append(tagLinks, tag.Link())
65+
}
66+
}
67+
68+
tagList := strings.Join(tagLinks, ", ")
69+
70+
// Tags
71+
tagsStartStr := "<!-- TAGS:START -->"
72+
tagsEndStr := "<!-- TAGS:END -->"
73+
74+
re := fmt.Sprintf("`%s\n.*\n%s`", tagsStartStr, tagsEndStr)
75+
rg := regexp.MustCompile(re)
76+
77+
newContent := rg.ReplaceAllString(page.Content, tagList)
78+
79+
if page.Content != newContent {
80+
// Swap the old content with the new content
81+
page.Content = newContent
82+
} else {
83+
// Append the tag list to the end of the page
84+
page.Content += fmt.Sprintf(
85+
"\n%s\n%s\n%s\n",
86+
tagsStartStr,
87+
tagList,
88+
tagsEndStr,
89+
)
90+
}
91+
92+
return true
93+
}
94+
5395
// PageFromFilePath creates and returns a Page instance from a file path
5496
func PageFromFilePath(filePath string) *Page {
5597
page := new(Page)

0 commit comments

Comments
 (0)