因需求调研模板引擎解析
有点粗暴,暂时只有这个想法了~
模板文件(html)
{sdsn:arclist menuid='11'}
<a href='[field:id/]'>[field:title/]</a>
{/sdsn:arclist}
读取html文件
cwd, _ := os.Getwd()
content, err := os.ReadFile(cwd + "/template/index.html")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
// 删除换行符
htmlStr := strings.ReplaceAll(strings.ReplaceAll(string(content), "\n", ""), "\r", "")
正则解析标签
//匹配标签
re := regexp.MustCompile(`\{\s*sdsn:arclist(.+?)\}(.+?)\{\s*/sdsn:arclist\s*\}`)
//匹配标签中的所属栏目id
reMenuId := regexp.MustCompile(`typeid=['"](.*?)['"]`)
//匹配标签中的字段
reField := regexp.MustCompile(`\[\s*field:(.+?)\s*/\]`)
替换替换标签字符串
这里需要考虑从数据库查出的数据,需要对其转化成map格式,然后根据匹配到k 使用map取值,并且对其替换
for _, match := range re.FindAllStringSubmatch(htmlStr, -1) {
// 查询列表数据
var articles []structs.Article
var temHtml string
sql := utils.DB.Debug().Table("article")
if len(reMenuId.FindStringSubmatch(match[1])) > 0 {
sql = sql.Where("menu_id = ?", reMenuId.FindStringSubmatch(match[1])[1])
}
sql.Find(&articles)
for i := 0; i < len(articles); i++ {
liStr := match[2]
for _, f := range reField.FindAllStringSubmatch(match[2], -1) {
articlesMap, _ := utils.ToMap(articles[i], "json")
liStr = strings.ReplaceAll(liStr, f[0], fmt.Sprintf("%v", articlesMap[f[1]]))
}
temHtml = temHtml + liStr
}
htmlStr = strings.ReplaceAll(htmlStr, match[0], temHtml)
}