diff --git a/README.md b/README.md index 8f97447..d972d78 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,7 @@ If a panic occurs inside a gtf function, the function will silently swallow the * [join](#join) * [slice](#slice) * [random](#random) +* [striptags](#striptags) @@ -675,6 +676,28 @@ This function also supports unicode strings. +#### striptags + +Makes all possible efforts to strip all [X]HTML tags from given value. + +* supported value types : string + +This function also supports unicode strings. + +``` +{{ value | striptags }} +``` + +**Examples** + +1. If input is {{ "text" | striptags }}, the output will be "text". +1. If input is {{ "안녕하세요" | striptags }}, the output will be "안녕하세요". (unicode) +1. If input is {{ "text 안녕하세요" | striptags }}, the output will be "text 안녕하세요". + + + + + ## Goal The first goal is implementing all built-in template filters of Django & Jinja2. diff --git a/gtf.go b/gtf.go index b40c32c..836c9ce 100644 --- a/gtf.go +++ b/gtf.go @@ -7,10 +7,13 @@ import ( "math/rand" "net/url" "reflect" + "regexp" "strings" "time" ) +var striptagsRegexp = regexp.MustCompile("<[^>]*?>") + // recovery will silently swallow all unexpected panics. func recovery() { recover() @@ -419,6 +422,9 @@ var GtfFuncMap = template.FuncMap{ return "" }, + "striptags": func(s string) string { + return strings.TrimSpace(striptagsRegexp.ReplaceAllString(s, "")) + }, } // gtf.New is a wrapper function of template.New(http://golang.org/pkg/text/template/#New). diff --git a/gtf_test.go b/gtf_test.go index ac63631..c74fec7 100644 --- a/gtf_test.go +++ b/gtf_test.go @@ -357,6 +357,15 @@ func TestGtfFuncMap(t *testing.T) { ParseTest(&buffer, "{{ . | random }}", false) AssertEqual(t, &buffer, "") + + ParseTest(&buffer, "{{ . | striptags }}", "text") + AssertEqual(t, &buffer, "text") + + ParseTest(&buffer, "{{ . | striptags }}", "안녕하세요") + AssertEqual(t, &buffer, "안녕하세요") + + ParseTest(&buffer, "{{ . | striptags }}", "text 안녕하세요") + AssertEqual(t, &buffer, "text 안녕하세요") } func TestInject(t *testing.T) {