0

It is possible to inline an above-the-fold/critical css file in a django template ?

I was thinking of something like:

<style>{% inline "css/home.above.css" %}</style>

Which would result in:

<style>html {...} body {...} {content of the css file}</style>

But I haven't found any ressources in that regards.

1
  • 1
    Answers on this question say that you can use {% include %} tag. I haven't tried it, though. Another way I can think of is you can read/open the css file in your views and put it in your template context. Commented May 26, 2017 at 19:30

1 Answer 1

1

To expand upon my comment, this is how you can pass your CSS file to your template context.

def my_view(request):
    with open('../path/to/style.css') as infile:
        css = infile.read()
        # if you want to remove newlines, uncomment the next line
        # css = css.replace('\n', '')
        # if you want to remove tabs, uncomment the next line
        # css = css.replace('\t, '')

    return render(request, 'template.html', {'css': css})

Then, in your template, you can use {{ css }} to access the whole CSS file.


NOTE: Instead of manually removing newlines and tabs from CSS, I think it's better to use a CSS compressor. For example, if you're using 4 spaces instead of tabs, then those extra spaces won't be stripped.

This library seems good - csscompressor.

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

1 Comment

Thanks. I will try to inline with django-compressor.

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.