Search code examples
javascriptnode.jsexpressswig-template

for loop swig, nodejs


i'm trying to create a loop..

here's the javascript:

for (var j = 0; j < b; j++) {
if(j%4 == 0 && j != 0){
    newTable.appendChild(tr);
    tr = document.createElement('tr');        
}

i want max 4 cells each rows, so if i have 9 cells, i should have 2 full rows and 1 row with only one cell.

how do we set a condition with swig like javascript?

here's my html code:

<table id="asdf">
            <tbody>

            {% if styles in styles.length %}
            <tr>                     
              {% for style in styles %}
                  <td>
                    <table border="1">
                        <tbody>
                        <tr><td><a href="{{style.a}}"><div style="width: 175px;height: 250px" id="products"><img id="img" src="{{style.img}}" ></div></a></td></tr>
                        <tr><td id="styleno">{{style.style}}</td></tr>
                        </tbody>
                    </table>
                  </td>{% endfor %}
            </tr> {% endif %}
            </tbody>
        </table>
    </div>

Solution

  • {% for style in styles %}
    {% if loop.index0 % 4 === 0 && loop.index0 !== 0 %}
    <tr>
    {% endif %}
            <td>
                <table border="1">
                            <tbody>
    
                            <tr>
                            <td><a href="{{style.a}}"><div style="width: 175px;height: 250px" id="products"><img id="img" src="{{style.img}}" ></div></a></td></tr>
                            <tr><td id="styleno">{{style.style}}</td></tr>
                            </tbody>
                        </table>
                        </td>
    
    {% endfor %}