// Output 1: "The Go Programming Language"
// Output 2: "The Go Programming Language"
}
+
+// This example demonstrates registering two custom template functions
+// and how to overwite one of the functions after the template has been
+// parsed. Overwriting can be used, for example, to alter the operation
+// of cloned templates.
+func ExampleTemplate_funcs() {
+
+ // Define a simple template to test the functions.
+ const tmpl = `{{ . | lower | repeat }}`
+
+ // Define the template funcMap with two functions.
+ var funcMap = template.FuncMap{
+ "lower": strings.ToLower,
+ "repeat": func(s string) string { return strings.Repeat(s, 2) },
+ }
+
+ // Define a New template, add the funcMap using Funcs and then Parse
+ // the template.
+ parsedTmpl, err := template.New("t").Funcs(funcMap).Parse(tmpl)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if err := parsedTmpl.Execute(os.Stdout, "ABC\n"); err != nil {
+ log.Fatal(err)
+ }
+
+ // [Funcs] must be called before a template is parsed to add
+ // functions to the template. [Funcs] can also be used after a
+ // template is parsed to overwrite template functions.
+ //
+ // Here the function identified by "repeat" is overwritten.
+ parsedTmpl.Funcs(template.FuncMap{
+ "repeat": func(s string) string { return strings.Repeat(s, 3) },
+ })
+ if err := parsedTmpl.Execute(os.Stdout, "DEF\n"); err != nil {
+ log.Fatal(err)
+ }
+ // Output:
+ // abc
+ // abc
+ // def
+ // def
+ // def
+}