总的来说,我的目标是用通过flask传递到jinja循环中的字典中的数据动态更新html中的表。
在试图通过在jinja2循环中传递在pythonFlask中创建的字典中的数据来填充html表时,我不断地得到错误:“jinja2.exceptions.UndefinedError:'results'未定义”。
我已经在Flask中正确地定义了我的字典、return/render语句和jinja2循环,但由于某种原因,它因内部服务器错误而失败,声称它是未定义的。
我当前的代码如下。。。
jinja2/html:
{% extends "hw12_home.html" %}
{% block header %} Word counter! {% endblock %}
{% block paragraph %} Type or paste any text in to count. {% endblock %}
{% block body %}
<form action="/wordCount" method="POST">
<textarea name = "wordCount_text" rows = "20" cols = "125"></textarea> <br>
<input type ="Submit" value = "Count Words!">
</form>
<table id = "word_table">
<tr>
<th> Word: </th>
<th> Count: </th>
</tr>
{% for key, value in results.items() %}
<tr> <td> {{ key }} </td> <td> {{ value }} </td></tr>
{% endfor %}
</table>
{% endblock %}
pythonFlask:
@app.route('/wordCount' , methods= ['GET', 'POST'])
def wordCount ():
if request.method == 'POST':
wordCount_text = request.form['wordCount_text']
wordCount_split = wordCount_text.split(' ')
results = {}
uniqueWords = []
for word in wordCount_split:
if word != '' and word not in uniqueWords:
uniqueWords.append(word)
results[word] = ""
for word in uniqueWords:
count = 0
for word_2 in wordCount_split:
if word == word_2:
count += 1
results[word] = str(count)
return render_template('word_count.html', results=results)
return render_template('word_count.html')
我在jinja循环中尝试了以下操作:.iteritems()、.itervalues()
我已经查看了堆栈上的多个解决方案,甚至web资源,它们显示的语法模仿了我的设置,但出于某种原因,“结果”仍然显示为未定义。
我知道我的字典已经设置好了,我期待的结果要归功于以下测试打印声明:
enter image description here
我还尝试过像这样在return/render语句中传递字典,但也不起作用:
enter image description here
我期待着一张这样的桌子。。。
enter image description here
最初,我尝试使用两个列表和一个嵌套的jinja2 for循环,但嵌套的循环会在分解并继续包含第一个循环中的数据之前完成迭代,从而生成如下表:
enter image description here
我这次尝试的jinja/html代码如下:
{% for i in uniqueWords %}
<tr> <td> {{ i }} </td>
{% for j in countList %}
<td> {{ j }} </td> </tr>
{% endfor %}
{% endfor %}
总的来说,我不明白为什么我被告知结果是不确定的。
感谢您提前提出任何建议。