这里使用pongo2这个模版引擎库进行md文件渲染GitHub - flosch/pongo2: Django-syntax like template-engine for Go
package main
import (
"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 main
import (
"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")
}