1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-07 22:22:29 +08:00

feat: add TemplateReplace

This commit is contained in:
dudaodong
2024-09-06 11:04:54 +08:00
parent f9e5ec9096
commit 93be25920f
5 changed files with 151 additions and 1 deletions

View File

@@ -704,3 +704,26 @@ func Rotate(str string, shift int) string {
return sb.String()
}
// TemplateReplace replaces the placeholders in the template string with the corresponding values in the data map.
// The placeholders are enclosed in curly braces, e.g. {key}.
// for example, the template string is "Hello, {name}!", and the data map is {"name": "world"},
// the result will be "Hello, world!".
// Play: todo
func TemplateReplace(template string, data map[string]string) string {
re := regexp.MustCompile(`\{(\w+)\}`)
result := re.ReplaceAllStringFunc(template, func(s string) string {
key := strings.Trim(s, "{}")
if val, ok := data[key]; ok {
return val
}
return s
})
result = strings.ReplaceAll(result, "{{", "{")
result = strings.ReplaceAll(result, "}}", "}")
return result
}