Home > Software design >  Display results from two lists in one list with one loop (Flask - Python)
Display results from two lists in one list with one loop (Flask - Python)

Time:12-29

I'm trying to display my result on an HTML page (index.html) in a list of links. I have two lists, first containing all the WebSite Name and the second their links. I want to display the name as clickable items.

My Lists :

name_list = ['Name1','Name2','Name3']
link_list = ['Link1','Link2','Link3']

What my Python code returns:

return render_template('index.html' , name_list =name_list , link_list =link_list , len1 = len(name_list ))

HTML code:

{% for i in range(0, len1) %}
      <li><a href={{link_list[i]}} >{{ name_list[i] }}</a></li> 
{% endfor %}

But I have two Errors:

First with the len1 , because when I change my code to range(0, 5) (or any int) this line works.

TypeError: 'Undefined' object cannot be interpreted as an integer

The second occured when I'm adding the postion of the element I want name_list[i].

jinja2.exceptions.UndefinedError: 'name_list' is undefined

CodePudding user response:

Here is a simple approach to solve your problem:

You combine the two lists with the python's builtin function zip():

name_list = ['Name1','Name2','Name3']
link_list = ['Link1','Link2','Link3']
name_link_list = zip(name_list, link_list)

You simply return this:

return render_template('index.html' , name_link_list=name_link_list)

This returns a list of tuples of the form [('Name1', 'Link1'), ('Name2', 'Link2'), ...], which you get in your HTML code using the index of each element. 0 for the name, 1 for the link.

And finally your HTML code:

<ul>
    {% for i in name_link_list %}
        <li><a href={{i[1]}} >{{ i[0] }}</a></li> 
    {% endfor %}
</ul>
  • Related