0

That's my code:

{%block content%}
    {% for i in posts %}
        {% set x = x + 1 -%}
        <p style="border: 1px solid black; padding: 5px 5px; border-radius: 5px;">{{ i[x] }}</p>
    {% endfor %}
    <form action="{{ url_for('redirectposts') }}">
        <button class="btn btn-primary" type="submit">Posts</button>
    </form>
{%endblock%}

Btw, I set x as 0 in the render_template, as you can see here:

return render_template('index.html', titulo="Home", posts=lista, x = 0)

The 'posts' variable receives a large list with some strings. I want to know how can I iterate those strings, starting at the index[0] to the last one, putting them in the "p" tag, as a loop that repeat that structure.

I tried the code above, but it only returned the first index, not the rest, I don't know what am I doing wrong.

2 Answers2

1

Further, if you want both an index and a value, you can do something like

{% for i, v in e %}
<div>{{ i }}: {{ v }}</div>
{% endfor %}

and pass in an enumeration.

@app.route('/')
def index():
    stuff = ['first', 'second', 'third']
    return render_template('index.html', e = enumerate(stuff))

which will give you

0: first
1: second
2: third
Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46
0

You don't need the index. Try:

 {% for i in posts %}
        <p style="border: 1px solid black; padding: 5px 5px; border-radius: 5px;">{{ i }}</p>
    {% endfor %}

It automatically loops over the items with the for loop. This would also mean you don't need to pass x into the template.