1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +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
}

View File

@@ -724,3 +724,18 @@ func ExampleRotate() {
// oHell
// loHel
}
func ExampleTemplateReplace() {
template := `Hello, my name is {name}, I'm {age} years old.`
data := map[string]string{
"name": "Bob",
"age": "20",
}
result := TemplateReplace(template, data)
fmt.Println(result)
// Output:
// Hello, my name is Bob, I'm 20 years old.
}

View File

@@ -766,3 +766,47 @@ func TestRotate(t *testing.T) {
assert.Equal(tt.expected, Rotate(tt.input, tt.shift))
}
}
func TestTemplateReplace(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestTemplateReplace")
t.Run("basic", func(t *testing.T) {
template := `Hello, my name is {name}, I'm {age} years old.`
data := map[string]string{
"name": "Bob",
"age": "20",
}
expected := `Hello, my name is Bob, I'm 20 years old.`
result := TemplateReplace(template, data)
assert.Equal(expected, result)
})
t.Run("not found", func(t *testing.T) {
template := `Hello, my name is {name}, I'm {age} years old.`
data := map[string]string{
"name": "Bob",
}
expected := `Hello, my name is Bob, I'm {age} years old.`
result := TemplateReplace(template, data)
assert.Equal(expected, result)
})
t.Run("brackets", func(t *testing.T) {
template := `Hello, my name is {name}, I'm {{age}} years old.`
data := map[string]string{
"name": "Bob",
"age": "20",
}
expected := `Hello, my name is Bob, I'm {20} years old.`
result := TemplateReplace(template, data)
assert.Equal(expected, result)
})
}