Louise Louise - 1 month ago 11
Python Question

Easy for-loop in Flask

I have a problem with my for-loop. I have never worked with either python or flask before. I want to iterate over a list and use the elements in it. The list looks like this:

NAVBAR_LIST = ["/", "Home", "/database/", "Database", "Log out"]


My code looks like this:

{% for topic in NAVBAR_LIST %}
{{topic}}
{{topic}}
{{topic}}
{{topic}}
{{topic}}
{% endfor %}


Now my output is:

/ / / / / / Home Home Home Home Home Home /database/ /database/ /database/ /database/ /database/ /database/ Database Database Database Database Database Database Log out Log out Log out Log out Log out Log out

How should i do if i want it to output one of each? like:

/Home/database/DatabaseLog out

Answer

For each time it loops it will iterate over an element in the array and print it so:

{% for topic in NAVBAR_LIST %}
    {{topic}}
{% endfor %}

Will print each element once.

Following on from your comment you can print out each element where you want like this:

{{ NAVBAR_LIST[0] }}
{{ NAVBAR_LIST[1] }}
{{ NAVBAR_LIST[2] }}
{{ NAVBAR_LIST[3] }}
{{ NAVBAR_LIST[4] }}

Array keys start at 0 you can access each element with the key.