diff options
author | Jimmy Sawczuk <github@jimmysawczuk.com> | 2016-07-05 04:35:24 +0300 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2016-07-05 20:52:45 +0300 |
commit | fbf48824aeab6833c1550d9e6bf1b99c3d84cb75 (patch) | |
tree | ac462fbac0d36874acb9f1c339b59f45bd3b26cd /tpl | |
parent | 770df77b22eeb0183e622b5b25203b96556b1f95 (diff) |
tpl: Add a querify function to generate query strings inside templates
The query function will take a set of parameters specified like a dict and return a url.Values object which can be .Encode'd into a query string.
Example:
<a href="http://www.google.com?{{ (querify "q" "test" "page" 3).Encode | safeHTML }}">Search</a>
Returns:
<a href="http://www.google.com?page=3&q=test">Search</a>
Closes #2257
Diffstat (limited to 'tpl')
-rw-r--r-- | tpl/template_funcs.go | 17 | ||||
-rw-r--r-- | tpl/template_funcs_test.go | 2 |
2 files changed, 19 insertions, 0 deletions
diff --git a/tpl/template_funcs.go b/tpl/template_funcs.go index db785cbc0..fc9fc1f64 100644 --- a/tpl/template_funcs.go +++ b/tpl/template_funcs.go @@ -27,6 +27,7 @@ import ( "html" "html/template" "math/rand" + "net/url" "os" "reflect" "regexp" @@ -1745,6 +1746,21 @@ func sha1(in interface{}) (string, error) { return hex.EncodeToString(hash[:]), nil } +// querify converts the given parameters into a url.Values object +func querify(params ...interface{}) (url.Values, error) { + qs := url.Values{} + vals, err := dictionary(params...) + if err != nil { + return url.Values{}, fmt.Errorf("querify keys must be strings") + } + + for name, value := range vals { + qs.Add(name, url.QueryEscape(fmt.Sprintf("%v", value))) + } + + return qs, nil +} + func init() { funcMap = template.FuncMap{ "absURL": func(a string) template.HTML { return template.HTML(helpers.AbsURL(a)) }, @@ -1794,6 +1810,7 @@ func init() { "partial": partial, "plainify": plainify, "pluralize": pluralize, + "querify": querify, "readDir": readDirFromWorkingDir, "readFile": readFileFromWorkingDir, "ref": ref, diff --git a/tpl/template_funcs_test.go b/tpl/template_funcs_test.go index 3f7f6cb64..bccee4c9e 100644 --- a/tpl/template_funcs_test.go +++ b/tpl/template_funcs_test.go @@ -103,6 +103,7 @@ modBool: {{modBool 15 3}} mul: {{mul 2 3}} plainify: {{ plainify "Hello <strong>world</strong>, gophers!" }} pluralize: {{ "cat" | pluralize }} +querify: {{ (querify "foo" 1 "bar" 2 "baz" "with spaces").Encode | safeHTML }} readDir: {{ range (readDir ".") }}{{ .Name }}{{ end }} readFile: {{ readFile "README.txt" }} relURL 1: {{ "http://gohugo.io/" | relURL }} @@ -154,6 +155,7 @@ modBool: true mul: 6 plainify: Hello world, gophers! pluralize: cats +querify: bar=2&baz=with%2Bspaces&foo=1 readDir: README.txt readFile: Hugo Rocks! relURL 1: http://gohugo.io/ |