【问题标题】:Inline CSS file in django templatedjango 模板中的内联 CSS 文件
【发布时间】:2017-05-27 03:51:58
【问题描述】:

可以在 django 模板中内联首屏/关键 css 文件吗?

我在想这样的事情:

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

这会导致:

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

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

【问题讨论】:

  • this question 上的回答说你可以使用{% include %} 标签。不过,我还没有尝试过。我能想到的另一种方法是您可以在视图中读取/打开 css 文件并将其放入模板上下文中。

标签: css django performance pagespeed


【解决方案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.

【讨论】:

  • 谢谢。我将尝试与 django-compressor 内联。
猜你喜欢
  • 2014-06-10
  • 2020-08-11
  • 2015-02-19
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 2010-11-07
  • 2016-02-09
  • 1970-01-01
相关资源
最近更新 更多