django模板中的内联CSS文件

时间:2017-05-26 18:07:51

标签: css django performance pagespeed

可以在django模板中内联一个折叠/关键的css文件吗?

我想的是:

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

哪会导致:

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

但在这方面我没有找到任何资源。

1 个答案:

答案 0 :(得分:1)

为了扩展我的评论,您可以将CSS文件传递给模板上下文。

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

然后,在您的模板中,您可以使用{{ css }}来访问整个CSS文件。

注意:我认为使用CSS压缩器不是手动删除CSS中的换行符和标签页。例如,如果您使用4个空格而不是制表符,那么这些额外的空格将无法被删除。

这个图书馆似乎很好 - csscompressor

相关问题