Flask:使用 url_for 提供没有前导斜杠的资产

duh*_*ime 7 python routing relative-path flask

我正在开发一个 Flask 应用程序,用于url_for指定一些静态资产(js、css 等)的路由。以下是其中一个模板的示例:

<script src='{{ url_for('static', filename='js/search.js') }}'></script>
Run Code Online (Sandbox Code Playgroud)

当它被渲染成 html 时,路径如下所示:

<script src='/static/js/search.js'></script>
Run Code Online (Sandbox Code Playgroud)

是否可以修改此行为,以便从呈现的脚本路径中删除前导斜杠?目标是呈现以下内容:

<script src='static/js/search.js'></script>
Run Code Online (Sandbox Code Playgroud)

我将非常感谢其他人可以就这个问题提供的任何见解!

小智 1

我在加载自定义静态路径上的 css 文件时遇到了类似的问题。一种解决方法可能是更改应用程序的 ROOT_DIRECTORY,但这对我的应用程序不起作用,因为我只需要更改静态路径。

我使用了 static_folder 和 static_url_path 的组合:

STATIC_URL_PATH = '/your/custom/path/static' # Where the css is stored
STATIC_FOLDER = 'your/custom/path/static'

app = Flask(__name__, static_folder=STATIC_FOLDER,
            static_url_path=STATIC_URL_PATH)
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,主要区别是开头的 / ,但这使得应用程序能够找到 css。