all repos — searchix @ 149cbe7681607eb48f47df14c7a39e6f289fb7b6

Search engine for NixOS, nix-darwin, home-manager and NUR users

refactor(templates): render partials with less hackiness
Alan Pearce alan@alanpearce.eu
Wed, 15 May 2024 12:35:40 +0200
commit

149cbe7681607eb48f47df14c7a39e6f289fb7b6

parent

5624cf8f6427064dd17de40acd1d3fdfe8332e96

M frontend/templates/blocks/options.gotmplfrontend/templates/blocks/options.gotmpl
@@ -1,4 +1,3 @@-{{- template "results" . -}}
 {{- define "results" }}
   {{- if gt .Results.Total 0 }}
     <section id="results">
M frontend/templates/blocks/search.gotmplfrontend/templates/blocks/search.gotmpl
@@ -1,6 +1,3 @@-{{- template "main" . }}
-{{- template "js" . }}
-
 {{- define "main" }}
   <form id="search">
     <label for="query">{{ .Source.Name }} option search</label>
M internal/server/mux.gointernal/server/mux.go
@@ -106,7 +106,7 @@ ExtraHeadHTML: config.Web.ExtraHeadHTML, 			Sources:       config.Importer.Sources,
 			Version:       *versionInfo,
 		}
-		err := templates["index"].ExecuteTemplate(w, "index.gotmpl", indexData)
+		err := templates["index"].Execute(w, indexData)
 		if err != nil {
 			http.Error(w, err.Error(), http.StatusInternalServerError)
 		}
@@ -192,9 +192,9 @@ } 
 			if r.Header.Get("Fetch") == "true" {
 				w.Header().Add("Content-Type", "text/html; charset=utf-8")
-				err = templates["options"].ExecuteTemplate(w, "options.gotmpl", tdata)
+				err = templates["options"].ExecuteTemplate(w, "results", tdata)
 			} else {
-				err = templates["options"].ExecuteTemplate(w, "index.gotmpl", tdata)
+				err = templates["options"].Execute(w, tdata)
 			}
 			if err != nil {
 				slog.Error("template error", "template", "options", "error", err)
M internal/server/templates.gointernal/server/templates.go
@@ -47,7 +47,10 @@ return input 	},
 }
 
-func loadTemplate(layoutFile string, filename string) (*template.Template, error) {
+func loadTemplate(
+	layoutFile string,
+	filenames ...string,
+) (*template.Template, error) {
 	tpl := template.New("index.gotmpl")
 
 	tpl.Funcs(templateFuncs)
@@ -56,8 +59,8 @@ if err != nil { 		return nil, errors.WithMessage(err, "could not parse layout template")
 	}
 
-	if filename != "" {
-		_, err = tpl.ParseFS(frontend.Files, filename)
+	if len(filenames) > 0 {
+		_, err = tpl.ParseFS(frontend.Files, filenames...)
 		if err != nil {
 			return nil, errors.WithMessage(err, "could not parse template")
 		}
@@ -72,7 +75,7 @@ templates := make(TemplateCollection, 0) 
 	layoutFile := path.Join(templateDir, "index.gotmpl")
 
-	index, err := loadTemplate(layoutFile, "")
+	index, err := loadTemplate(layoutFile)
 	if err != nil {
 		return nil, err
 	}
@@ -84,7 +87,7 @@ if err != nil { 		return nil, errors.WithMessage(err, "could not glob block templates")
 	}
 	for _, fullname := range templatePaths {
-		tpl, err := loadTemplate(layoutFile, glob)
+		tpl, err := loadTemplate(layoutFile, glob, fullname)
 		if err != nil {
 			return nil, err
 		}