3

New to building front-end web and this will be my first time raising a question here. I am using Flask to try it out but my code seems a bit of a mess. Is there a simpler way to implement this code?

            {% for data in dataList %}
              <tr>
                {% for d in data %}
                  {% if data.index(d) == 0 %}
                    {% if dataList.index(data) == 0 %}
                      <td> <input type="radio" name="option" value="{{d}}" checked> </td>
                    {%else%}
                      <td> <input type="radio" name="option" value="{{d}}"> </td>
                    {%endif%}
                  {%else%}
                    {% if d %}
                      <td> {{d}} </td>
                    {%endif%}
                  {%endif%}
                {% endfor %}
              </tr>
            {% endfor %}
Mike
  • 43
  • 6

2 Answers2

1

Inside of a for-loop block, you can access some special variables. loop.first equals True in first iteration.

{% for data in dataList %}
{% set outer_loop = loop %}
  <tr>
    {% for d in data %}
      {% if loop.first %}
        <td><input type="radio" name="option" value="{{d}}" {{"checked" if outer_loop.first}}></td>
      {% elif d %}
        <td>{{d}}</td>
      {% endif %}
    {% endfor %}
  </tr>
{% endfor %}
r-m-n
  • 14,192
  • 4
  • 69
  • 68
0

If I was given this code to tidy up, I would probably end up with something like the following:

{% for data in dataList %}
    <tr>
        {% for d in data %}
            {% if data.index(d) == 0 %}
                <td>
                    <input type="radio" name="option" value="{{d}}" {% if dataList.index(data) == 0 %} checked {% endif %}>
                </td>
            {% else %}
                {% if d %}
                    <td>{{d}}</td>
                {% endif %}
            {% endif %} ## data.index(d) == 0
        {% endfor %} ## d in data
    </tr>
{% endfor %} ## data in dataList
MTCoster
  • 5,868
  • 3
  • 28
  • 49