fix: compute TemplateName in ResultView instead of using dynamic template function
Go html/template doesn't support function calls as template names in
{{template (func .Arg) .}}. Instead, precompute TemplateName in
FromResponse and use {{template .TemplateName .}} in the template.
This commit is contained in:
parent
7d3c82214b
commit
f0a65e2b8c
2 changed files with 12 additions and 11 deletions
|
|
@ -36,7 +36,12 @@ type PageData struct {
|
|||
}
|
||||
|
||||
// ResultView is a template-friendly wrapper around a MainResult.
|
||||
type ResultView contracts.MainResult
|
||||
type ResultView struct {
|
||||
contracts.MainResult
|
||||
// TemplateName is the actual template to dispatch to, computed from Template.
|
||||
// "videos" maps to "video_item", everything else maps to "result_item".
|
||||
TemplateName string
|
||||
}
|
||||
|
||||
// PageNumber represents a numbered pagination button.
|
||||
type PageNumber struct {
|
||||
|
|
@ -63,14 +68,6 @@ func init() {
|
|||
|
||||
funcMap := template.FuncMap{
|
||||
"urlquery": template.URLQueryEscaper,
|
||||
// templateForResult returns the template name to use for a result.
|
||||
// Defaults to "result_item"; use "video_item" for video results.
|
||||
"templateForResult": func(tmpl string) string {
|
||||
if tmpl == "videos" {
|
||||
return "video_item"
|
||||
}
|
||||
return "result_item"
|
||||
},
|
||||
}
|
||||
|
||||
tmplFull = template.Must(template.New("").Funcs(funcMap).ParseFS(tmplFS,
|
||||
|
|
@ -113,7 +110,11 @@ func FromResponse(resp contracts.SearchResponse, query string, pageno int) PageD
|
|||
// Convert results.
|
||||
pd.Results = make([]ResultView, len(resp.Results))
|
||||
for i, r := range resp.Results {
|
||||
pd.Results[i] = ResultView(r)
|
||||
tmplName := "result_item"
|
||||
if r.Template == "videos" {
|
||||
tmplName = "video_item"
|
||||
}
|
||||
pd.Results[i] = ResultView{MainResult: r, TemplateName: tmplName}
|
||||
}
|
||||
|
||||
// Convert answers (they're map[string]any — extract string values).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue