这里使用pongo2这个模版引擎库进行md文件渲染GitHub - flosch/pongo2: Django-syntax like template-engine for Go
package mainimport ("fmt""github.com/flosch/pongo2/v6""os"
)func main() {// 假设有一个名为 data 的 map 数组data := []map[string]interface{}{{"Name": "John", "Age": 30, "Country": "USA"},{"Name": "Alice", "Age": 25, "Country": "Canada"},{"Name": "Bob", "Age": 35, "Country": "UK"},}// 使用 Pongo2 模板定义表格templateString := `
# User Data| Name | Age | Country |
|:-------:|:-----:|:---------:|
{% for user in data %}| {{ user.Name }} | {{ user.Age }} | {{ user.Country }} |
{% endfor %}`// 解析模板template, err := pongo2.FromString(templateString)if err != nil {fmt.Printf("Error parsing template: %v\n", err)return}// 执行模板output, err := template.Execute(pongo2.Context{"data": data})if err != nil {fmt.Printf("Error executing template: %v\n", err)return}// 打印输出或将其保存到文件fmt.Println(output)// 也可以将输出保存到文件file, err := os.Create("output.md")if err != nil {fmt.Printf("Error creating file: %v\n", err)return}defer file.Close()file.WriteString(output)
}
Go 语言原生如下示例:
package mainimport ("fmt""strings"
)func main() {data := []map[string]interface{}{{"Name": "Alice", "Age": 25, "City": "New York"},{"Name": "Bob", "Age": 30, "City": "San Francisco"},// ... (更多数据)}mdTable := generateMarkdownTable(data)fmt.Println(mdTable)
}func generateMarkdownTable(data []map[string]interface{}) string {var builder strings.Builder// 表头headers := make([]string, 0)for key := range data[0] {headers = append(headers, key)}writeRow(&builder, headers)// 表格数据for _, row := range data {values := make([]string, 0)for _, key := range headers {value := fmt.Sprintf("%v", row[key])values = append(values, value)}writeRow(&builder, values)}return builder.String()
}func writeRow(builder *strings.Builder, values []string) {builder.WriteString("| ")builder.WriteString(strings.Join(values, " | "))builder.WriteString(" |\n")
}