我有一个关于网址更改的基本问题。
假设我有一个HTML页面http://example.com/create
,它包含一些带有输入字段的表单。从这个输入字段我想创建一个python列表,该列表应该用于生成另一个HTML页面http://example.com/show_list
,其中包含基于python列表值的列表。
因此http://example.com/create
的观点是:
@app.route('/create', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
some_list = parse_form_data_and_return_list(...)
return render_template( "show_list.html", some_list=some_list) #here's the problem!
return render_template( "create.html")
假设parse_form_data_and_return_list(...)
接受用户输入并返回包含string
个值的列表。
我在困扰我的那条线上添加了评论。我会在一秒钟内回到它,但首先会给你一个应该在用户输入后加载的页面模板(http://example.com/show_list
):
{% block content %}
<ul class="list">
{% for item in some_list %}
<li>
{{ item }}
</li>
{% endfor %}
</ul>
{% endblock content %}
基本上这很好用。列表值“传递”到Jinja模板,并显示列表。
如果您现在再次查看我的路线方法,您可以看到我只是render_template
来显示shwo_list
页面。对我来说,这有一个缺点。该网址不会更改为http://example.com/show_list
,但会保留在http://example.com/create
。
所以我考虑为route
创建一个自己的show_list
,并在create()
方法中调用redirect
,而不是直接渲染下一个模板。像这样:
@app.route('/show_list')
def tasklist_foo():
return render_template( "show_list.html" )
但在这种情况下,我看不出如何将list
对象传递给show_list()
。我当然可以将列表中的每个项目解析为URL(因此将其发布到http://example.com/show_list
),但这不是我想要做的。
正如您已经认识到的那样,我对网络开发很陌生。我想我只是使用了错误的模式,或者没有找到一个简单的API函数来完成这个技巧。所以我请你告诉我一个解决问题的方法(很快就会总结):渲染show_list
模板,并使用{中创建的列表将网址从http://example.com/create
更改为http://example.com/show_list
{1}}方法/路线。
答案 0 :(得分:8)
如果列表不是很长,你可以在查询字符串上传递它,比如用逗号分隔:
comma_separated = ','.join(some_list)
return redirect(url_for('show_list', some_list=comma_separated))
# returns something like 'http://localhost/show_list?some_list=a,b,c,d'
然后在视图中的模板中,您可以像这样迭代它们:
{% for item in request.args.get('some_list', '').split(',') %}
{{ item }}
{% endfor %}
对于较长的列表,或者如果您不想在查询字符串上公开它,您还可以将列表存储在session中:
session['my_list'] = some_list
return redirect(url_for('show_list'))
然后在模板中:
{% for item in session.pop('my_list', []) %}
{{ item }}
{% endfor %}
答案 1 :(得分:0)
除了将列表存储在会话中之外,您还可以简单地更改表单操作以发布到新路由。然后处理&#39; show_list&#39;中的表单数据。路线并渲染你的模板。
表格标题:
<form action="{{ url_for('show_list') }}" method="post">
更新了show_list路线:
@app.route('/show_list', methods=['GET', 'POST'])
def show_list():
if request.method == 'POST':
some_list = parse_form_data_and_return_list(...)
return render_template("show_list.html")
else:
# another way to show your list or disable GET
return render_template("show_list.html")
我不一定反对使用会话存储,但我认为不使用会话存储更加清晰,因为您不必担心清除会话变量。