我的Flask路线的一半需要变量say /<variable>/add
或/<variable>/remove
。如何创建指向这些位置的链接?使用url_for()创建Flask中的动态URL
url_for()
需要一个参数为函数路由到但我不能添加参数?
我的Flask路线的一半需要变量say /<variable>/add
或/<variable>/remove
。如何创建指向这些位置的链接?使用url_for()创建Flask中的动态URL
url_for()
需要一个参数为函数路由到但我不能添加参数?
它采用关键字参数的变量:
url_for('add', variable=foo)
参考使用的the Flask API document for flask.url_for()
其他的示例代码段用于连接JS或CSS到您的模板如下。
<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
在烧瓶url_for
用于创建一个URL,以防止具有在整个应用程序改变URL的开销(包括在模板中)。如果没有url_for
,如果您的应用的根网址发生变化,那么您必须在链接所在的每个页面中对其进行更改。
语法:url_for('name of the function of the route','parameters (if required)')
它可以作为:
@app.route('/index')
@app.route('/')
def index():
return 'you are in the index page'
现在,如果你有一个链接索引页:您可以使用此:
<a href={{ url_for('index') }}>Index</a>
你可以做例如:很多东西,例如:
@app.route('/questions/<int:question_id>'): #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):
return ('you asked for question{0}'.format(question_id))
对于上面我们可以使用:
<a href = {{ url_for(find_question,question_id=1) }}>Question 1</a>
这样你可以简单地传递参数!
我有一个问题,在第一个示例中,索引方法作为字符串传递,而在第二个方法中,find_question被传递为变量。为什么? –
@AnandTyagi这是你的意思吗? [URL路由](http://flask.pocoo.org/docs/0.12/quickstart/#url-building) –
意思是这个函数是'def add(variable)'? – endolith
@ndndolith,是的。传递给'url_for'的kwargs将作为Flask中的变量规则路由的函数参数传递 – highvolt