Created
September 20, 2016 16:23
-
-
Save shavit/3c4653a594ba7b8474e1df4471ce5573 to your computer and use it in GitHub Desktop.
Create custom helpers for HTML and XML templates in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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