duanlv1366 2017-08-15 02:09
浏览 232
已采纳

如何从template.FuncMap返回HTML模板?

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,

  • 写回答

1条回答 默认 最新

  • dougou7008 2017-08-15 04:43
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么