feat(template): 添加分类获取函数及HTML模板渲染支持

- 新增GetCategories函数用于提取产品分类
- 添加GetCategoriesNoHtml和GetCategoriesHtml函数处理HTML内容
- 在main11中注册新的模板函数并解析rangeTemplate11.html
- 创建rangeTemplate11.html模板文件实现多种分类展示方式
- 支持在模板中使用getCats、getCatsNoHtml、getCatsHtml和lower函数
- 引入strings包以支持字符串小写转换功能
This commit is contained in:
2025-10-23 22:17:35 +08:00
parent 72e5761277
commit 51c7ed5cbf
2 changed files with 81 additions and 0 deletions

View File

@@ -3,6 +3,7 @@ package main
import (
"html/template"
"os"
"strings"
)
func Exec(t *template.Template) {
@@ -31,6 +32,38 @@ func ExecList(t *template.Template) {
Printfln("")
}
func GetCategories(products []Product) (categories []string) {
catMap := map[string]string{}
for _, p := range products {
if catMap[p.Category] == "" {
catMap[p.Category] = p.Name
categories = append(categories, p.Name)
}
}
return
}
func GetCategoriesNoHtml(products []Product) (categories []string) {
catMap := map[string]string{}
for _, p := range products {
if catMap[p.Category] == "" {
catMap[p.Category] = p.Name
categories = append(categories, p.Name+" <b>p.Category</b>")
}
}
return
}
func GetCategoriesHtml(products []Product) (categories []template.HTML) {
catMap := map[string]string{}
for _, p := range products {
if catMap[p.Category] == "" {
catMap[p.Category] = p.Name
categories = append(categories, template.HTML(p.Name+" <b>p.Category</b>"))
}
}
return
}
func main() {
main1()
main2()
@@ -42,6 +75,25 @@ func main() {
main9()
main10_0()
main10_1()
main11()
}
func main11() {
Printfln("\nmain11:")
funcTemplates := template.New("funcTemplates")
funcTemplates.Funcs(map[string]interface{}{
"getCats": GetCategories,
"getCatsNoHtml": GetCategoriesNoHtml,
"getCatsHtml": GetCategoriesHtml,
"lower": strings.ToLower,
})
t, err := funcTemplates.ParseFiles("templates/rangeTemplate11.html")
if err != nil {
Printfln("Error:%v", err.Error())
return
}
ExecList(t.Lookup("mainTemplate"))
}
func main10_1() {
Printfln("\nmain10_1:")

View File

@@ -0,0 +1,29 @@
{{ define "mainTemplate" -}}
<h2>There area {{ len . }} products in the source data .</h2>
<h1>Display $index $value:</h1>
{{ range $index,$value := getCats . -}}
<h1>{{ $index }} Category : {{ $value }}</h1>
{{ end }}
<h1>Display . :</h1>
{{ range getCats . -}}
<h1>Category : {{ . }}</h1>
{{ end }}
<h1>Display . no html :</h1>
{{ range getCatsNoHtml . -}}
<h1>Category : {{ . }}</h1>
{{ end }}
<h1>Display . html :</h1>
{{ range getCatsHtml . -}}
<h1>Category : {{ . }}</h1>
{{ end }}
<h1>Display . lower :</h1>
{{ range getCats . -}}
<h1>Category : {{ lower . }}</h1>
{{ end }}
{{- end -}}