Search code examples
arraysgorevelarray-indexing

How index starts with 1 in revel Framework


  <tr>
      <td>rank</td>
      <td>abc</td>
  </tr>
  {{ range $index,$abc := .abc }}
     <tr>
      <td>{{$index}}</td> // 0
      <td>{{$abc}}</td>
     </tr>
  {{end}}
  1. how to {{$index}} starts with 1

    {{add $index 1}} - unction "add" not defined

    {{$index + 1}} - illegal number syntax: "+"


Solution

  • You can pass a custom function into your controller's ViewArgs as a variable.

    controller.ViewArgs["addOne"] = func (i int64) {
        return i+1
    }
    

    You can then use $.addOne to access the function in a loop. To use it as a function, you have to add a call keyword before it:

      <tr>
          <td>rank</td>
          <td>abc</td>
      </tr>
      {{ range $index, $abc := .abc }}
         <tr>
          <td>{{call $.addOne $index}}</td> // $index + 1
          <td>{{$abc}}</td>
         </tr>
      {{end}}