使用url_for()将Flask变量从HTML发送回Flask [英] Sending Flask variable from HTML back to Flask with url_for()

查看:63
本文介绍了使用url_for()将Flask变量从HTML发送回Flask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个小的工作板,每个工作卡都是从列表中的flask动态插入的(目前,稍后将是SQL DB)

I'm trying to create a little job board, each job card is dynamically inserted from flask from a list (for now, will be an SQL DB later)

当用户单击按钮View Task时,我希望它转到另一个页面,其中更详细地显示任务/作业.

When the user clicks the button View Task I want it to go to another page where it displays the task/job in more detail.

我要附加到该按钮的是作业/任务ID.

What I want attached to that button is the job/task ID.

这就是我希望/期望按钮起作用的方式

This is how I'd want/expect the button to function

{% for task in available_tasks %}
<div>
   <a href="{{ url_for('view_task', task_id={{ task['id'] }}) }}">View Task</a>
</div>
{% endfor %}

然后可以将其粘贴到以ID作为参数并获取完整作业/任务信息的路由中.

This could then be pasted into a route that would take the ID as an argument and fetch the full job/task information.

app.route('/view_task/<task_id>')
def view_task(task_id):
   task_data = task_database[taskid]
   return render_template('detailed_view.html', task_info=task_data)

我的问题是href="url_for('view_task', task_id={{ task['id'] }})"无法正常工作,有办法吗?

My problem is href="url_for('view_task', task_id={{ task['id'] }})" doesn't work, is there a way to do this?

推荐答案

您生成了输出href="url_for('view_task', task_id=<some id>)",因此文本文本url_for(..)在生成的HTML中并传递到您的浏览器,并且HTML引擎无法识别该字符串作为任何内容的有效URL.

You generated the output href="url_for('view_task', task_id=<some id>)", so the literal text url_for(..) is in the HTML generated and delivered to your browser, and HTML engines don't recognise that string as a valid URL for anything.

您需要将url_for()函数放在{{ ... }}括号中,而不仅仅是任务ID值:

You need to put the url_for() function in the {{ ... }} brackets, not just the task id value:

href="{{ url_for('view_task', task_id=task['id']) }}"

然后只有url_for()实际上被视为要执行的Jinja2表达式,HTML生成的点将包含href="http://localhost:5000/view_task/<some id>"字符串.

Only then is url_for() actually treated as an expression for Jinja2 to execute, at which point the HTML produces will contain the href="http://localhost:5000/view_task/<some id>" string.

这篇关于使用url_for()将Flask变量从HTML发送回Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆