Golang html/template.JS type examples

package html/template

JS encapsulates a known safe EcmaScript5 Expression, for example, (x + y * z()). Template authors are responsible for ensuring that typed expressions do not break the intended precedence and that there is no statement/expression ambiguity as when passing an expression like "{ foo: bar() }\n'foo'", which is both a valid Expression and a valid Program with a very different meaning.

Golang html/template.JS type usage examples

Example 1:

 // Makes a FuncMap with useful things on it for page rendering
 func NewDefaultFuncMap() template.FuncMap {
  return template.FuncMap{
 "rawhtml": func(s string) template.HTML { return template.HTML(s) },
 "rawjs": func(s string) template.JS { return template.JS(s) },
 "rawcss": func(s string) template.CSS { return template.CSS(s) },
  }
 }

Example 2:

 data := []interface{}{
 `<b> "foo%" O'Reilly &bar;`,
 CSS(`a[href =~ "//example.com"]#foo`),
 HTML(`Hello, <b>World</b> &amp;tc!`),
 HTMLAttr(` dir="ltr"`),
 JS(`c && alert("Hello, World!");`),  // <--- here
 JSStr(`Hello, World & O'Reilly\x21`),
 URL(`greeting=H%69&addressee=(World)`),
  }

Example 3:

 func runtime_safeJS(arg string) template.JS {
  return template.JS(arg)
 }

References :

https://github.com/bradleypeabody/gotako/blob/master/gotako.go

http://golang.org/pkg/html/template/#JS

Advertisement