Template for a Grid


I am trying to create a template for a bootstrap grid, so fixed number of columns per row. I have got this far, which produces well formed html and handles the row closure, but it does not handle the required fixed number of columns in the last row. Been solved before? Or is there a better approach?

Thanks in advance

{{ $cols := 3}}
            {{ range $key, $value := .Data.Pages}}
            {{ if modBool $key $cols }}
            <div class="row">
                    <li>{{ .Render "li" }}</li>
            {{ if modBool (add $key 1) $cols }}

As it turns out I don’t think I need to do this, as bootstrap grids don’t need to be formed in the precise way html tables do. But since I managed to get something working…

{{ $cols := 4}}
{{ $len := len .Site.Pages }}
{{$extraRequired := mod (sub $cols (mod $len $cols)) $cols }}

Columns: {{ $cols}}, Elements: {{ $len }}, Extra Elements Required: {{$extraRequired}}
    {{ range $key, $value := .Site.Pages}}
    {{ $isLastElem := not (sub (sub $len 1) $key)}}
    {{ if modBool $key $cols }}
        <td style="border:1px solid green">{{ $key }}:{{ .Title }} (last one: {{$isLastElem}})</td>
        {{ if and $isLastElem $extraRequired }}
        {{range first $extraRequired .Site.Data.config.bootstrapCols}}
        <td style="border:1px solid red">blank</td>
        {{ if or (modBool (add $key 1) $cols) $isLastElem }}

So various uses of mod and modBool to work out if you need to close the row and if you need some extra columns. The cheat was to create a blank array in a data file and use that to drive the inner range loop to add the extra columns. My data file (config.json) just contained:

“bootstrapCols”: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]

1 Like