From 323944585a7cf6183bf1bb6300ce82c3bd0ac4f8 Mon Sep 17 00:00:00 2001 From: Brendan Anderson Date: Thu, 7 Feb 2019 13:39:58 -0500 Subject: [PATCH] add findreplace filter --- README.md | 15 +++++++++++++++ gtf.go | 5 +++++ gtf_test.go | 3 +++ gtf_text_test.go | 3 +++ 4 files changed, 26 insertions(+) diff --git a/README.md b/README.md index 355088f..d8f2b51 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ If a panic occurs inside a gtf function, the function will silently swallow the ### Index * [replace](#replace) +* [findreplace](#findreplace) * [default](#default) * [length](#length) * [lower](#lower) @@ -245,6 +246,20 @@ If value is "The Go Programming Language", the output will be "TheGoProgrammingL +#### findreplace + +Replaces all instances of the first argument with the second. + +* supported value types : string +* supported argument types : string + +``` +{{ value | findreplace " " "-" }} +``` +If value is "The Go Programming Language", the output will be "The-Go-Programming-Language". + + + #### default 1. If the given string is ""(empty string), uses the given default argument. diff --git a/gtf.go b/gtf.go index e9ca2f3..f4c43b1 100644 --- a/gtf.go +++ b/gtf.go @@ -26,6 +26,11 @@ var GtfTextFuncMap = textTemplate.FuncMap{ return strings.Replace(s2, s1, "", -1) }, + "findreplace": func(s1 string, s2 string, s3 string) string { + defer recovery() + + return strings.Replace(s3, s1, s2, -1) + }, "title": func(s string) string { defer recovery() return strings.Title(s) diff --git a/gtf_test.go b/gtf_test.go index 37370de..32a8601 100644 --- a/gtf_test.go +++ b/gtf_test.go @@ -43,6 +43,9 @@ func TestGtfFuncMap(t *testing.T) { ParseTest(&buffer, "{{ \"The Go Programming Language\" | replace \" \" }}", "") AssertEqual(t, &buffer, "TheGoProgrammingLanguage") + ParseTest(&buffer, "{{ \"The Go Programming Language\" | findreplace \" \" \"X\" }}", "") + AssertEqual(t, &buffer, "TheXGoXProgrammingXLanguage") + ParseTest(&buffer, "{{ \"the go programming language\" | title }}", "") AssertEqual(t, &buffer, "The Go Programming Language") diff --git a/gtf_text_test.go b/gtf_text_test.go index 3afb396..4a48699 100644 --- a/gtf_text_test.go +++ b/gtf_text_test.go @@ -18,6 +18,9 @@ func TestTextTemplateGtfFuncMap(t *testing.T) { TextTemplateParseTest(&buffer, "{{ \"The Go Programming Language\" | replace \" \" }}", "") AssertEqual(t, &buffer, "TheGoProgrammingLanguage") + TextTemplateParseTest(&buffer, "{{ \"The Go Programming Language\" | findreplace \" \" \"X\" }}", "") + AssertEqual(t, &buffer, "TheXGoXProgrammingXLanguage") + TextTemplateParseTest(&buffer, "{{ \"The Go Programming Language\" | length }}", "") AssertEqual(t, &buffer, "27")