dongwuxie7976 2013-09-05 13:41
浏览 57

html / template if range index子句

I've got this template that parses multiple items of a slice onto the page. It does that really well.

However, I now want to use the very same template to parse a single value of the slice, based on the range index. The slice is used in multiple files so I can't just .Execute it like Slice[1:2]

{{ $bpi := .Index}}

{{ range $i, $elmt := .Slice }}
    {{ if $bpi.Equals $i }}
      <div>{{ .SliceContent }}</div>
    {{ end }}
{{ end }}

From what I've read is that the template isn't ment for computation, but if you've got a range index and if-statements in the html/template package it seems to me that I must be doing something wrong. I can write a FuncMap ofcourse, no problemo. But it doesn't seem right to me given these facts.

  • 写回答

1条回答 默认 最新

  • donglie7268 2013-09-06 04:13
    关注

    I am using something like this to conditionally include a default image or the first from a supplied slice of pictures. So I think this will provide you with the basis to do what you want. I check the slice has values, pulling the Nth item using the {{index .Slice n}} syntax as follows:

         {{ $idx := 2}}
         {{if .Pictures}}
           <img src="{{if .Pictures}}{{index .Pictures $idx}}{{end}}" alt="supplied first picture">
         {{else}}
           <img src="http://fpoimg.com/200x200?text=Placeholder(FPOimg.com)" alt="default picture">
         {{end}}
    

    Therefore you can do the following:

        {{ $bpi := .Index}}
    
        {{ if .Slice }}
            {{ index .Slice $bpi }}
        {{ end }}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?