]> Cypherpunks repositories - gostls13.git/commitdiff
exp/template: url filter.
authorDavid Symonds <dsymonds@golang.org>
Mon, 8 Aug 2011 06:29:57 +0000 (16:29 +1000)
committerDavid Symonds <dsymonds@golang.org>
Mon, 8 Aug 2011 06:29:57 +0000 (16:29 +1000)
R=r
CC=golang-dev
https://golang.org/cl/4837063

src/pkg/exp/template/doc.go
src/pkg/exp/template/exec_test.go
src/pkg/exp/template/funcs.go

index c374acec802a9b20aac4146a2cc31e6557d8d18f..796bc9d476246d77e528b2f6723dfedcba9a0e35 100644 (file)
@@ -244,6 +244,9 @@ Predefined global functions are named as follows.
                An alias for fmt.Sprintf
        println
                An alias for fmt.Sprintln
+       url
+               Returns the escaped value of the textual representation of
+               its arguments in a form suitable for embedding in a URL.
 
 The boolean functions take any zero value to be false and a non-zero value to
 be true.
index 4a13825bdb579ad910ddae111ea32de30405ce6f..50eefc3e854990799e871ddb14ec1a9ef3516405 100644 (file)
@@ -283,6 +283,9 @@ var execTests = []execTest{
        // JavaScript.
        {"js", `{{js .}}`, `It\'d be nice.`, `It'd be nice.`, true},
 
+       // URL.
+       {"url", `{{"http://www.example.org/"|url}}`, "http%3A%2F%2Fwww.example.org%2F", nil, true},
+
        // Booleans
        {"not", "{{not true}} {{not false}}", "false true", nil, true},
        {"and", "{{and false 0}} {{and 1 0}} {{and 0 true}} {{and 1 1}}", "false 0 0 1", nil, true},
index 1de44fcb2c6cba040037d2b20746d35fff4b4dbc..5e912e014ca99f314beab7ff05f6d48d4e4804b1 100644 (file)
@@ -7,6 +7,7 @@ package template
 import (
        "bytes"
        "fmt"
+       "http"
        "io"
        "os"
        "reflect"
@@ -31,6 +32,7 @@ var funcs = map[string]reflect.Value{
        "print":   reflect.ValueOf(fmt.Sprint),
        "printf":  reflect.ValueOf(fmt.Sprintf),
        "println": reflect.ValueOf(fmt.Sprintln),
+       "url":     reflect.ValueOf(URLEscaper),
 }
 
 // addFuncs adds to values the functions in funcs, converting them to reflect.Values.
@@ -318,3 +320,16 @@ func JSEscaper(args ...interface{}) string {
        }
        return JSEscapeString(s)
 }
+
+// URLEscaper returns the escaped value of the textual representation of its
+// arguments in a form suitable for embedding in a URL.
+func URLEscaper(args ...interface{}) string {
+       s, ok := "", false
+       if len(args) == 1 {
+               s, ok = args[0].(string)
+       }
+       if !ok {
+               s = fmt.Sprint(args...)
+       }
+       return http.URLEscape(s)
+}