From 332e983da476974805a3a0d53bfedaebe73a9fcb Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sun, 19 May 2024 22:14:25 +0200 Subject: Get rid of most of preprocess funcs, only Image leftover for convenience --- src/render/methods.go | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) (limited to 'src/render/methods.go') diff --git a/src/render/methods.go b/src/render/methods.go index ee22dfd..2b8675b 100644 --- a/src/render/methods.go +++ b/src/render/methods.go @@ -5,11 +5,13 @@ import ( "context" "fmt" "html/template" + "io" "net/url" "path" "path/filepath" "strconv" "strings" + txttpl "text/template" "dev.mediocregopher.com/mediocre-blog.git/src/gmi/gemtext" "dev.mediocregopher.com/mediocre-blog.git/src/post" @@ -196,11 +198,41 @@ func (m *Methods) GetPostSeriesNextPrevious( return res, nil } -func (m *Methods) PostGemtextBody(p post.StoredPost) (string, error) { +type preprocessPostPayload struct { + RootURL URLBuilder + image func(args ...string) (string, error) +} + +func (p preprocessPostPayload) Image(args ...string) (string, error) { + return p.image(args...) +} + +// preprocessPostBody interprets the Post's Body as a text template which may +// use any of the functions found in PreprocessFunctions (all must be set). It +// executes the template and writes the result to the given writer. +func (m *Methods) preprocessPostBody(into io.Writer, p post.Post) error { + tpl := txttpl.New("") + + tpl, err := tpl.Parse(p.Body) + if err != nil { + return fmt.Errorf("parsing post body as template: %w", err) + } + + err = tpl.Execute(into, preprocessPostPayload{ + RootURL: m.RootURL(), + image: m.preprocessFuncs.Image, + }) + if err != nil { + return fmt.Errorf("executing post body as template: %w", err) + } + return nil +} + +func (m *Methods) PostGemtextBody(p post.StoredPost) (string, error) { buf := new(bytes.Buffer) - if err := p.PreprocessBody(buf, m.preprocessFuncs); err != nil { + if err := m.preprocessPostBody(buf, p.Post); err != nil { return "", fmt.Errorf("preprocessing post body: %w", err) } @@ -222,7 +254,7 @@ func (m *Methods) PostGemtextBody(p post.StoredPost) (string, error) { func (m *Methods) PostHTMLBody(p post.StoredPost) (template.HTML, error) { bodyBuf := new(bytes.Buffer) - if err := p.PreprocessBody(bodyBuf, m.preprocessFuncs); err != nil { + if err := m.preprocessPostBody(bodyBuf, p.Post); err != nil { return "", fmt.Errorf("preprocessing post body: %w", err) } -- cgit v1.2.3