【问题标题】:Template Tags not supported in Stylesheets样式表不支持模板标签
【发布时间】:2020-10-26 05:59:08
【问题描述】:

假设我在 Django 中的静态文件中创建了一个样式表。 所以其他一切工作正常。只是当我使用这条线时,它给出了一个错误

.PostProfilePic {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-image: url('{{ Profile.ProfilePic.url }}');
  background-size: cover;
  background-position: center;
  position: relative;
  top: 5px;
}

假设有一个类名PostProfilePic,我想使用数据库中的图像作为我的背景图像。那我们怎么做???

错误在这一行

background-image: url('{{ Profile.ProfilePic.url }}');

上面写着cannot resolve file

当我在 HTML 页面中的标签之间使用这种样式时,如下所示,它完全可以正常工作

<style>
  .PostProfilePic {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-image: url('{{ Profile.ProfilePic.url }}');
    background-size: cover;
    background-position: center;
    position: relative;
    top: 5px;
  }
</style>

虽然制作单独的.css 文件会带来麻烦...对此有什么解决方案吗??

【问题讨论】:

  • 您无法在样式表中访问这些变量。我建议在您的模板中编写内联 css,您可以在其中访问变量或使用 javascript
  • 问题解决了吗?你看过我的回答吗?
  • 是的,我在模板中包含了需要 {{ }} 的样式......以及样式表中的所有其他内容。
  • @KartikeyVaish 如果答案对您的问题有所帮助,请单击答案旁边的复选标记将其标记为已接受。请参阅here 了解更多信息

标签: python html css django django-templates


【解决方案1】:

外部.css 文件中的background-image: url('{{ Profile.ProfilePic.url }}'); 将不起作用,因为django 不会呈现变量。注意url css 函数应该满足以下约束

url() CSS 函数用于包含文件。参数为绝对 URL、相对 URL 或数据 URI。

因此它不会显示任何内容,因为 '{{ Profile.ProfilePic.url }}' 无法解析任何内容。

花括号{{-}} 只能在模板中呈现变量,因此它在您的第二次尝试中起作用,因为它是模板中CSS 的内部定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多