7

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>

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!

duhaime
  • 25,611
  • 17
  • 169
  • 224
  • What do you expect to happen if you're not on a root-level page? `../../../static/js/search.js`? Why do you want to avoid the absolute URL in the first place? – Blender Mar 12 '18 at 00:42
  • 1
    @blender Ah yes. Well I need to serve this beast using a reverse proxy on Apache, such that users who request IP/cats/meow/ get the Flask index route content. But right now the static asset requests fail. I tried setting `app.config['SERVER_NAME'] = IP/cats/meow/` but that does not appear to solve the problem. I'd be grateful for any thoughts you might have on the subject! – duhaime Mar 12 '18 at 00:48
  • app.config['APPLICATION_ROOT'] seems promising--investigating now... – duhaime Mar 12 '18 at 00:54
  • This is probably what you're looking for: https://stackoverflow.com/a/37308920/464744, specifically the last code example – Blender Mar 12 '18 at 00:57
  • @Blender Thanks! Was just reading my way down that thread... – duhaime Mar 12 '18 at 00:58

1 Answers1

1

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.

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)

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.

Divadrare
  • 26
  • 2