Does django-compressor work with template inherita

2019-02-13 10:05发布

问题:

I'm using django-compressor to compress my site's static CSS and Javascript files. Since I serve my site's static assets via Amazon S3, I'm also using django-storages to upload my files to S3.

Here's my issue: I'm trying to make a clean base.html template that all my site's other templates can inherit and extend. Here's what it looks like currently:

{% load compress %}

<html>
 <head>
  <!-- test -->
  {% compress css %}
   <link rel="stylesheet" type="text/css" media="screen" href="{{ STATIC_URL }}css/styles.css" />
  {% endcompress %}

  {% compress css %}
  {% block css %}{% endblock %}
  {% endcompress %}

  {% compress js %}
  {% block js %}{% endblock %}
  {% endcompress %}
 </head>
 <body>
  {% block body %}{% endblock %}
 </body>
</html>

As you can see, what I'm attempting to do here is allow my templates that inherit this template to override the css and js blocks, so they can define their own css and javascript to be compressed. Unfortunately, that's not what happens.

When I run python manage.py compress (to have django-compressor analyze my templates and generated the compressed javascript and css code), it doesn't actually find my included css and javascript files.

For instance, here's my site's index.html template:

{% block css %}
 {{ block.super }}
 <link rel="stylesheet" type="text/css" media="screen" href="{{ STATIC_URL }}css/index.css" />
{% endblock %}

When I attempt to visit that page on my site, I get an error saying that the compressed file doesn't exist.

I believe that what's happening is that the python manage.py compress command isn't inspecting my templates that inherit from base.html. And since it isn't analyzing them, it isn't generating any compressed code.

I'd really like to get this working, because the only workaround I've found so far is to manually add {% compress %}...{% endcompress %} tags in every single template file I have explicitly. I just hate to do that since it repeats so much code everywhere :(

Any advice would be greatly appreciated.

回答1:

I suppose you are using offline compression, in which case the template inheritance does not work as one would expect. See these issues relevant to this "problem":

  • https://github.com/jezdez/django_compressor/issues/171
  • https://github.com/jezdez/django_compressor/issues/175