Files
pages/internal/server/macro_expand.go
T

152 lines
2.0 KiB
Go

package server
import (
"fmt"
"html"
"regexp"
"strings"
)
var childrenMacroRe = regexp.MustCompile(`\{\{children(?::([^}\s]+))?(?:\s+exclude=([^}]+))?\}\}`)
func splitExcludePatterns(
raw string,
) []string {
var out []string
for _, p := range strings.Split(raw, ",") {
p = strings.TrimSpace(p)
if p == "" {
continue
}
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
out = append(out, p)
}
return out
}
func isExcludedPath(
path string,
patterns []string,
) bool {
for _, p := range patterns {
if path == p ||
strings.HasPrefix(
path,
p+"/",
) {
return true
}
}
return false
}
func (s *Server) expandMacros(
body string,
currentPath string,
) string {
return childrenMacroRe.ReplaceAllStringFunc(
body,
func(m string) string {
matches :=
childrenMacroRe.FindStringSubmatch(m)
targetPath :=
currentPath
excludeRaw := ""
if len(matches) >= 2 &&
strings.TrimSpace(matches[1]) != "" {
targetPath =
strings.TrimSpace(
matches[1],
)
}
if len(matches) >= 3 {
excludeRaw =
strings.TrimSpace(
matches[2],
)
}
if !strings.HasPrefix(targetPath, "/") {
targetPath = "/" + targetPath
}
excludes :=
splitExcludePatterns(
excludeRaw,
)
children, err :=
s.store.ListChildPaths(
targetPath,
)
if err != nil {
return ""
}
var b strings.Builder
b.WriteString(
`<section class="children-list">`,
)
b.WriteString("<ul>")
for _, child := range children {
if isExcludedPath(
child,
excludes,
) {
continue
}
name :=
strings.TrimPrefix(
child,
targetPath,
)
name =
strings.TrimPrefix(
name,
"/",
)
b.WriteString(
fmt.Sprintf(
`<li><a href="%s">%s</a></li>`,
html.EscapeString(child),
html.EscapeString(name),
),
)
}
b.WriteString("</ul>")
b.WriteString("</section>")
return b.String()
},
)
}