烧瓶:使用url_for提供资产而不会导致斜杠 [英] Flask: serve assets without leading slash using url_for

查看:84
本文介绍了烧瓶:使用url_for提供资产而不会导致斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a Flask app that uses url_for to specify the route to some static assets (js, css, etc). Here's an example from one of the templates:

<script src='{{ url_for('static', filename='js/search.js') }}'></script>

将其呈现为html时,路径如下所示:

When this gets rendered into html, the path looks like this:

<script src='/static/js/search.js'></script>

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

Is it possible to modify this behavior such that the leading slash is dropped from the rendered script path? The goal is to render the following:

<script src='static/js/search.js'></script>

对于其他人可以在此问题上提供的任何见解,我将不胜感激!

I'd be very grateful for any insights others can offer on this question!

推荐答案

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

I was having a similar issue with loading a css file that was on a custom static path. One fix could be to change the ROOT_DIRECTORY of the application, but this didn't work for my application as I only need to change the static path.

我使用了static_folder和static_url_path的组合:

I used a combination of static_folder and 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)

您可以看到,主要区别是开头的/,但这使应用程序能够找到CSS。

As you can see, the main difference is the leading / in the beginning, but this made the app to be able to find the css.

这篇关于烧瓶:使用url_for提供资产而不会导致斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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