为什么要使用Flask的url_for? [英] Why use Flask's url_for?
问题描述
我想知道使用url_for
在模板和应用程序代码中生成链接的背后原因.
I'd like to know the reasoning behind using url_for
to generate links in templates and the application code.
这样做有什么好处?
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
和这个:
<ul>
<li><a href="{{ url_for('index') }}">Home</a></li>
<li><a href="{{ url_for('about') }}">About Us</a></li>
<li><a href="{{ url_for('contact') }}">Contact</a></li>
</ul>
不是对路径进行硬编码?
Instead of hard coding the paths?
推荐答案
来自Flask的文档,
flask.url_for(endpoint, **values)
使用提供的方法生成指向给定端点的URL.
Generates a URL to the given endpoint with the method provided.
目标端点未知的变量参数是
作为查询参数附加到生成的URL.如果一个的值
查询参数为None
,将跳过整个对.万一有蓝图
处于活动状态时,您可以通过以下方式快捷地引用相同的蓝图
在本地终结点之前加点(.
).
Variable arguments that are unknown to the target endpoint are
appended to the generated URL as query arguments. If the value of a
query argument is None
, the whole pair is skipped. In case blueprints
are active you can shortcut references to the same blueprint by
prefixing the local endpoint with a dot (.
).
现在,您可以使用url_for
对该端点进行反向匹配,而不是指定用于到达端点的静态URL.当您有可能要在运行时指定的参数时,此功能特别有用.
Now, instead of specifying static urls to reach an endpoint, you can use url_for
which does a reverse match for the endpoint. It is particularly useful when you have arguments which you might want to specify at runtime.
{{ url_for('events', user_id=user.id, year=2013) }}
/events/1388224/2013
生成的路径始终是绝对路径(以"/"开头),因此无论当前URL如何,它们都可以工作.他们还考虑了是否将应用程序安装在前缀而不是根目录(例如"/myapp/events/1/2013")上.
The paths generated are always absolute (start with a "/") so that they work regardless of the current URL. They also take into account if the application is mounted at a prefix rather than the root (like "/myapp/events/1/2013").
_external=True
参数可用于生成带有服务器名称的URL,以便可以在外部(例如电子邮件中)使用它们.
The _external=True
argument can be used to generate URLs with the server name so that they can be used externally, such as in email messages.
View your events: {{ url_for("events", user_id=user.id, year=2013, _external=True) }}
这篇关于为什么要使用Flask的url_for?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!