I asked this question upon https://groups.google.com/forum/#!topic/golang-nuts/CUbdaHkESJk but received no replies.
I'm writing a Web based media viewer and I've hit a snag about how to mark up different media.
My current code here: https://github.com/kaihendry/lk/blob/5de96f9fe012e9894deef7b9924f96dd8d9c806c/main.go#L181 is certainly wrong. I am puzzled how to use a template here in light of https://golang.org/pkg/html/template/#Template.Execute
All the examples I see of using template.FuncMap just use strings...
Reduced example: https://play.golang.org/p/mAue8SDDw6
Ideally I would use html templates here and not fmt.Sprintf. Yes, I realise I am not HTML escaping the filename which is wrong, but I am not sure how to use HTML templates again from this function.
Thanks in advance for any guidance,
You should separate the logic (function) from presentation (template). The function registered in template.FuncMap
should not depends on template as its input to produce an output. If you want to return HTML template as the function output, you should generate it manually (using fmt.Sprintf
, etc.).
In your case, you can simply register a function to check the media type, then generate different output using template's {{if}}
action. The function may looks like:
func matchType(ext, s string) bool {
return strings.ToLower(ext) == strings.ToLower(path.Ext(s))
}
and the template looks like:
{{ range .Media }}<p>
{{if . | matchType ".jpg"}}<img src={{.}}>
{{else if . | matchType ".mp4"}}<video controls src={{.}}></video>
{{else}}{{.}}
{{end}}</p>
{{ end }}
A working example based on your reduced example: https://play.golang.org/p/U64_7UHZQU