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 }}
    
    评论

报告相同问题?