使用Flask处理CSS文件中的URL [英] Handling urls in css files with Flask

查看:56
本文介绍了使用Flask处理CSS文件中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在对CSS文件中的所有URL进行硬编码.这是其中的一行.

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;  }

我的html文件中的所有其他url是通过Flask的url_for函数提供的.我也尝试将其应用于我的css文件,但是它不起作用.我认为这是因为,当html文件从浏览器请求它们时,css文件会被提取.

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.

那么有没有办法通过Flask处理CSS中的URL?如果有,我应该吗?

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...

推荐答案

不,没有,这是有原因的.CSS文件及其喜欢的文件(JS,img等)被用作静态文件.实际上,您应该从CDN或至少从nginx提供服务(它确实缓存标头,压缩等).

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).

正确的方法:将nginx静态网址直接指向静态文件夹.更改CSS,HTML中的所有URL,使其指向/static/css/..、/static/js/ ...等.这将使它们基于URL,而不是基于文件.最后,将服务器代理到在更高端口上运行的Flask.(当我靠近计算机时,我会在此发布配置,但您可以在网上找到很多东西).

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).

不推荐的方式:提供一个动态URL,例如/ assets/< file-name>/,然后加载该文件,将其通过Jinja或您使用的任何模板解析器传递.这样,您可以使用模板标记来获取完整的URL,但是我完全不建议这样做.

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.

这篇关于使用Flask处理CSS文件中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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