feat(template): render template with default
This commit is contained in:
parent
df1f29b7ef
commit
5e17d38349
2 changed files with 33 additions and 12 deletions
|
|
@ -30,15 +30,11 @@ func (h *CreateNoteHandler) Handle(ctx context.Context, raw json.RawMessage) (an
|
|||
return nil, err
|
||||
}
|
||||
|
||||
data, err := template.GenerateTemplate(cmd.TemplatePath)
|
||||
data, err := template.RenderTemplate(cmd.TemplatePath, cmd.Title)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if data == nil {
|
||||
data = []byte("---\ntitle: " + cmd.Title + "\ntags: []\n---\n")
|
||||
}
|
||||
|
||||
tags, err := frontmatter.ParseTags(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
|||
|
|
@ -1,17 +1,42 @@
|
|||
package templatepackage template
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
package template
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
||||
func GenerateTemplate(templatePath string) ([]byte, error) {
|
||||
if templatePath == "" {
|
||||
return nil, nil
|
||||
}
|
||||
data, err := os.ReadFile(templatePath)
|
||||
func RenderTemplate(templatePath string, title string, slug string) ([]byte, error) {
|
||||
tmpl, err := readTemplate(templatePath, title)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return data, nil
|
||||
|
||||
r := strings.NewReplacer(
|
||||
"{{title}}", title,
|
||||
"{{date}}", time.Now().Format("2006-01-02"),
|
||||
"{{slug}}", slug,
|
||||
)
|
||||
|
||||
return []byte(r.Replace(string(tmpl))), nil
|
||||
}
|
||||
|
||||
func readTemplate(templatePath string, title string) ([]byte, error) {
|
||||
if _, err := os.Stat(templatePath); os.IsNotExist(err) {
|
||||
return createDefaultTemplate(title), nil
|
||||
}
|
||||
return os.ReadFile(templatePath)
|
||||
}
|
||||
|
||||
func createDefaultTemplate(title string) []byte {
|
||||
return []byte("---\ntitle: " + title + "\ndate: " + time.Now().Format("2006-01-02") + "\n---\n")
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue