Skip to content

Instantly share code, notes, and snippets.

@shavit
Created September 20, 2016 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shavit/3c4653a594ba7b8474e1df4471ce5573 to your computer and use it in GitHub Desktop.
Save shavit/3c4653a594ba7b8474e1df4471ce5573 to your computer and use it in GitHub Desktop.
Create custom helpers for HTML and XML templates in Go
content, err = ioutil.ReadFile("templates/rss.xml")
if err != nil {
panic(err)
}
//Custom template helpers
fm := template.FuncMap{"number": func(n int) string {
return strconv.Itoa(n)
}, "float": func(f float64) string {
return strconv.FormatFloat(f, 'f', -1, 64)
}, "objectid": func(id bson.ObjectId) string {
return id.Hex()
}}
type Feed struct {
Name string
Item []string
}
var feed Feed = new Feed{Name: "Custom Feed"}
t, err := template.New("rss").Funcs(fm).Parse(string(content))
if err != nil {
panic(err)
}
// The template output
buffer := bytes.NewBuffer(nil)
writer := io.Writer(buffer)
t.Execute(writer, &feed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment