1

I'm currently hardcoding all urls in css files. Here's one line of many of them.

.logo { background: url(**../imgs/logo.png**) no-repeat  0 10px; width: 169px; height: 40px;  }

All other urls in my html files are served via Flask's url_for function. I tried to apply this to my css files as well but it won't work. I'm assuming it is because css files are fetched when html files requests them from the browser.

So is there a way to handle urls in css via Flask? If there is, should I?

Just in case my directory structure is roughly

static/
    css/
    fonts/
    imgs/
    js/
templates/
uploads/
app.py and models.py and git, db, procfile etc...
1
  • 1
    Files referenced by CSS files are fetched relative to the CSS file. You can (and I think should) reference them the way you are currently doing it. Using an absolute URL breaks if you ever change the URL prefix of your static assets. Commented Mar 23, 2015 at 22:23

1 Answer 1

7

No, there isn't and there is a reason why. CSS files and their likes (JS, img etc) are served as static files. In fact you should be serving them from CDN or least from nginx (it does cache headers, compression etc).

Right way: point nginx static url to the static folders directly. Change all the URLs in CSS, HTML to point as /static/css/.., /static/js/... and so on. This will make them URL based rather than file based. Finally proxy the server to Flask running on higher port. (I will post config on this when I am near a computer but you can find plenty online).

Non-recommended way: serve a dynamic URL eg /assets/<file-name>/ and then load that file, pass it through Jinja or whatever template parser you're using. This way you can use template tags to get full URLs but I do not recommend this at all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.