0

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
2
  • 1
    Your code worked for me. This is probably a problem with your variable scope. Are you sure that name_list can be seen within your function? Commented Dec 28, 2021 at 21:08
  • You were right I had a problem of indentation in a function . It has solved an issue. Commented Dec 28, 2021 at 22:02

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Definitely a more efficient approach
It solves my problem thanks ! Moreover I discorved a new function thanks to your explenations ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.