Skip to content

Commit

Permalink
Merge pull request #1 from vgarvardt/master
Browse files Browse the repository at this point in the history
Added striptags function
  • Loading branch information
leekchan committed Feb 6, 2016
2 parents c102ce5 + 618ae28 commit db4ad0a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
23 changes: 23 additions & 0 deletions README.md
Expand Up @@ -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)



Expand Down Expand Up @@ -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 {{ "<strong>text</strong>" | striptags }}, the output will be "text".
1. If input is {{ "<strong><em>안녕하세요</em></strong>" | striptags }}, the output will be "안녕하세요". (unicode)
1. If input is {{ "<a href=\"http://example.com/\">text <strong>안녕하세요</strong></a>" | striptags }}, the output will be "text 안녕하세요".





## Goal
The first goal is implementing all built-in template filters of Django & Jinja2.

Expand Down
6 changes: 6 additions & 0 deletions gtf.go
Expand Up @@ -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()
Expand Down Expand Up @@ -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).
Expand Down
9 changes: 9 additions & 0 deletions gtf_test.go
Expand Up @@ -357,6 +357,15 @@ func TestGtfFuncMap(t *testing.T) {

ParseTest(&buffer, "{{ . | random }}", false)
AssertEqual(t, &buffer, "")

ParseTest(&buffer, "{{ . | striptags }}", "<strong>text</strong>")
AssertEqual(t, &buffer, "text")

ParseTest(&buffer, "{{ . | striptags }}", "<strong><em>안녕하세요</em></strong>")
AssertEqual(t, &buffer, "안녕하세요")

ParseTest(&buffer, "{{ . | striptags }}", "<a href=\"http://example.com/\">text <strong>안녕하세요</strong></a>")
AssertEqual(t, &buffer, "text 안녕하세요")
}

func TestInject(t *testing.T) {
Expand Down

0 comments on commit db4ad0a

Please sign in to comment.