Faild to display element in a list using jinja2

Hi guys,

I need to display all elements in a list which input to template.render(my_list). But got an error when run it.

Code:

import os
from jinja2 import Template

x = """
<p>Student name in Flask course</p>
<ul>
<!-- code block to loop all my_list --!>
{% for i in my_list %}
<li>{{ i }}</li>
{% endfor %}
</ul>
"""

# Create new instance Template
template = Template(x)

my_list = []
for i in range(0, 3):
    my_list.append(raw_input())
print my_list
# output is an unicode string
print template.render(my_list)

Error message

Traceback (most recent call last):
  File "E:/VS Code - Python/Pycharm/Building web applications with Flask_Code/chapter03/chapter03/ex05.py", line 22, in <module>
    print template.render(my_list)
  File "C:\Python27\lib\site-packages\jinja2\environment.py", line 984, in render
    vars = dict(*args, **kwargs)
ValueError: dictionary update sequence element #0 has length 4; 2 is required

Process finished with exit code 1

This mean my_list has type dict, not list ? I can print my_list without any error but failed to run print template.render(my_list)

help(Template.render)
Help on method render in module jinja2.environment:

render(*args, **kwargs) method of jinja2.environment.Template instance
    This method accepts the same arguments as the `dict` constructor:
    A dict, a dict subclass or some keyword arguments.  If no arguments
    are given the context will be empty.  These two calls do the same::
    
        template.render(knights='that say nih')
        template.render({'knights': 'that say nih'})
    
    This will return the rendered template as unicode string.

You can use either type of argument: a dict, or pass in keyword arguments.
In your case, it would be:

print template.render(my_list=my_list)

Be aware that the name my_list in your code is different from my_list in your template.

1 Like

Problem solved. Thank you so much. :smiley:
So it means we only can pass value to arguments like template.render(argument=value) ?

Or pass in a dict: Template.render({'key':'value'}) where key is the name in the template, value is the name in your code

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?