gpt4 book ai didi

python - 如何使用 Flask/Jinja2 获取基本 url?

转载 作者:太空狗 更新时间:2023-10-29 22:24:45 35 4
gpt4 key购买 nike

我有一个 base.html 模板,我想将其用于所有页面。这个 base.html 包含一个导航

<nav>
<li><a href="./home">Home</a></li>
<li><a href="./foo">bar</a></li>
</nav>

当我在同一级别时(例如 localhost:5000/whatever),这没问题,但是当我在子文件夹中时(例如,localhost:5000/whatever/插入) 链接断开。

这可以通过使相对链接成为绝对链接来解决,例如

<nav>
<li><a href="{{base_url}}/home">Home</a></li>
<li><a href="{{base_url}}/foo">bar</a></li>
</nav>

但是,我不知道如何获取base_url。如果可能,我想避免将 base_url 添加到每个 render_template 调用。而且,如果可能的话,我还想避免手动设置 base_url

这个问题是如何用 Flask/Jinja2 解决的?

最佳答案

不用担心基本 url;如果 homefooFlask 应用程序中的路由,请使用 url_for() function改为构建您的网址:

<nav>
<li><a href="{{ url_for('home') }}">Home</a></li>
<li><a href="{{ url_for('foo') }}">bar</a></li>
</nav>

另见 URL Building section Flask 快速入门文档:

Why would you want to build URLs using the URL reversing function url_for() instead of hard-coding them into your templates?

  1. Reversing is often more descriptive than hard-coding the URLs. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs.
  2. You can change your URLs in one go instead of needing to remember to manually change hard-coded URLs
  3. URL building handles escaping of special characters and Unicode data transparently.
  4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.
  5. If your application is placed outside the URL root, for example, in /myapplication instead of /, url_for() properly handles that for you.

关于python - 如何使用 Flask/Jinja2 获取基本 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45207969/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com