Use embed.FS for templates (#5303)

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
This commit is contained in:
utagawa kiki 2024-05-10 01:28:06 +09:00 committed by GitHub
parent 44a035f318
commit 8d3e047f8c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

15
main.go
View File

@ -3,6 +3,7 @@ package main
import ( import (
"bytes" "bytes"
"embed"
"errors" "errors"
"fmt" "fmt"
template2 "html/template" template2 "html/template"
@ -42,11 +43,11 @@ var staticFiles = []string{
"tmpl/robots.txt", "tmpl/robots.txt",
} }
// TODO: embed
// Templates // Templates
var tplIndex = template.Must(template.ParseFiles("tmpl/index.tmpl.html")) //go:embed tmpl/*.tmpl.html tmpl/*.tmpl.xml
var tplCategoryIndex = template.Must(template.ParseFiles("tmpl/category-index.tmpl.html")) var tplFs embed.FS
var tplSitemap = template.Must(template.ParseFiles("tmpl/sitemap.tmpl.xml"))
var tpl = template.Must(template.ParseFS(tplFs, "tmpl/*.tmpl.html", "tmpl/*.tmpl.xml"))
// Output files // Output files
const outDir = "out/" // NOTE: trailing slash is required const outDir = "out/" // NOTE: trailing slash is required
@ -152,7 +153,7 @@ func renderCategories(categories map[string]Category) error {
fmt.Printf("Write category Index file: %s\n", categoryIndexFilename) fmt.Printf("Write category Index file: %s\n", categoryIndexFilename)
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
if err := tplCategoryIndex.Execute(buf, category); err != nil { if err := tpl.Lookup("category-index.tmpl.html").Execute(buf, category); err != nil {
return fmt.Errorf("render category `%s`: %w", categoryDir, err) return fmt.Errorf("render category `%s`: %w", categoryDir, err)
} }
@ -186,7 +187,7 @@ func renderSitemap(categories map[string]Category) error {
fmt.Printf("Render Sitemap to: %s\n", outSitemapFile) fmt.Printf("Render Sitemap to: %s\n", outSitemapFile)
if err := tplSitemap.Execute(f, categories); err != nil { if err := tpl.Lookup("sitemap.tmpl.xml").Execute(f, categories); err != nil {
return fmt.Errorf("render sitemap: %w", err) return fmt.Errorf("render sitemap: %w", err)
} }
@ -352,7 +353,7 @@ func renderIndex(srcFilename, outFilename string) error {
data := map[string]interface{}{ data := map[string]interface{}{
"Body": template2.HTML(body), "Body": template2.HTML(body),
} }
if err := tplIndex.Execute(f, data); err != nil { if err := tpl.Lookup("index.tmpl.html").Execute(f, data); err != nil {
return err return err
} }