30/09/2018, 23:31
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:Python27libsite-packagesjinja2environment.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)
Bài liên quan
You can use either type of argument: a dict, or pass in keyword arguments.
In your case, it would be:
Be aware that the name
my_list
in your code is different frommy_list
in your template.Problem solved. Thank you so much.
So it means we only can pass value to arguments like
template.render(argument=value)
?Or pass in a dict:
Template.render({'key':'value'})
wherekey
is the name in the template,value
is the name in your code