diff --git a/README.md b/README.md index b830ef2..0b5d63c 100644 --- a/README.md +++ b/README.md @@ -170,21 +170,21 @@ Output: ``` -When returning HTML from a helper, you should return a `SafeString` if you don't want it to be escaped by default. When using `SafeString` all unknown or unsafe data should be manually escaped with the `EscapeString` method. +When returning HTML from a helper, you should return a `SafeString` if you don't want it to be escaped by default. When using `SafeString` all unknown or unsafe data should be manually escaped with the `Escape` method. ```go - tpl := raymond.MustParse("{{{link text url}}}") + tpl := raymond.MustParse("{{{link url text}}}") tpl.RegisterHelper("link", func(h *raymond.HelperArg) interface{} { - text := raymond.EscapeString(h.ParamStr(0)) - url := raymond.EscapeString(h.ParamStr(1)) + url := raymond.Escape(h.ParamStr(0)) + text := raymond.Escape(h.ParamStr(1)) return raymond.SafeString("" + text + "") }) ctx := map[string]string{ - "text": "This is a cool website", "url": "http://www.aymerick.com/", + "text": "This is a cool website", } result := tpl.MustExec(ctx) diff --git a/escape.go b/escape.go index 4b012c3..6a0363c 100644 --- a/escape.go +++ b/escape.go @@ -52,8 +52,10 @@ func escape(w writer, s string) error { return err } -// EscapeString escapes special HTML characters. -func EscapeString(s string) string { +// Escape escapes special HTML characters. +// +// It can be used by helpers that return a SafeString and that need to escape some content by themselves. +func Escape(s string) string { if strings.IndexAny(s, escapedChars) == -1 { return s } diff --git a/escape_test.go b/escape_test.go new file mode 100644 index 0000000..45183d0 --- /dev/null +++ b/escape_test.go @@ -0,0 +1,23 @@ +package raymond + +import "fmt" + +func ExampleEscape() { + tpl := MustParse("{{{link url text}}}") + + tpl.RegisterHelper("link", func(h *HelperArg) interface{} { + url := Escape(h.ParamStr(0)) + text := Escape(h.ParamStr(1)) + + return SafeString("" + text + "") + }) + + ctx := map[string]string{ + "url": "http://www.aymerick.com/", + "text": "This is a cool website", + } + + result := tpl.MustExec(ctx) + fmt.Print(result) + // Output: This is a <em>cool</em> website +} diff --git a/eval.go b/eval.go index 70e463d..26eb8d2 100644 --- a/eval.go +++ b/eval.go @@ -702,7 +702,7 @@ func (v *evalVisitor) VisitMustache(node *ast.MustacheStatement) interface{} { str := Str(expr) if !isSafe && !node.Unescaped { // escape html - str = EscapeString(str) + str = Escape(str) } return str