css - 在 css 文件中使用 Django 模板语法

标签 css django django-templates

我有一个 css 文件 home_global.css 其中包含以下内容:

body {
    background-image: url("{% static 'citator/citator.jpg' %}");
}

此静态文件使用以下方式加载:

<link rel="stylesheet" href="{% static 'citator/home_global.css' %}" type="text/css">

然而,背景图像的 url 预计不会解析,而是按字面意思解析。我想做的是在 css 文件中启用 Django 模板语法。

请注意,静态 URL 等都已正确设置,本题不涉及这些。

这个问题与我自己一个月前问的另一个问题非常相似: How to use django template syntax in static files

但是,那里提供的答案是特定于 javascript 的,并且特别指出“阻止这种情况的根本问题是将上下文传递给 render() 函数中提到的模板在 View 中(或任何其他函数,其行为方式相同,例如 render_to-response())。”

如果我理解正确,同样的限制在这里不适用。此外,我后来从 Django 文档中了解到,可以在各种文本文档中使用 Django 模板语法。因此在我看来,在这种情况下,我想在 css 文件中使用它,这应该是可能的。那么,我该怎么做呢?

最佳答案

正如您正确指出的那样,Django 模板可用于任何文本文件,而不仅仅是 HTML。但是,您需要确保它们由模板引擎呈现,提供特定的 URL 和 View 。

那样的话,您可以期望所有变量和标签都被插入,特别是将“静态”替换为 settings.STATIC_URL。 但是,我不会坚持在 CSS 文件本身的 url 前加上“/static/” ... 这会作弊,因为您宁愿动态呈现文件。

实践中:

元素/urls.py

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    ...
    path('css/home_global.css', TemplateView.as_view(
        template_name='home_global.css',
        content_type='text/css')
    ),
    ...
]

View 相当简单,已内联在 urls.py 中。 请注意,我还指定了适当的 mimetype“text/css”。

在这里,我在 url 前加了一个 'css/' 前缀,但这不是必需的,并且您的元素中不需要“css”文件夹; 只要确保模板引擎可以找到“home_global.css”;也就是说,将它放在任何已安装应用程序的/template/子文件夹中, 甚至在元素中,如果它在已安装的应用程序中列出:

元素/模板/home_global.css

{% load static %}

body {
    background-image: url("{% static 'citator/citator.jpg' %}");
}

您可以通过使用浏览器导航到此 url 来立即检查结果:

http://127.0.0.1:8000/css/home_global.css

呈现文档如下:

body {
    background-image: url("/static/citator/citator.jpg");
}

并根据需要将其包含在主模板中:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/css/home_global.css" type="text/css">
    ...

如果您需要呈现许多 css 文档,将文件名视为参数可能会很方便,然后对所有文档使用单个 View 。在这种情况下,为简单起见,我会选择基于函数的 View :

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    ...
    path('css/<str:filename>.css', views.css_renderer),
    ...
]

哪里:

View .py

from django.shortcuts import render


def css_renderer(request, filename):
    return render(request, filename + '.css', {}, content_type="text/css")

在你的主模板中:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/css/home_global.css" type="text/css">
    <link rel="stylesheet" href="/css/another.css" type="text/css">
    <link rel="stylesheet" href="/css/yet_another.css" type="text/css">
    ...

关于css - 在 css 文件中使用 Django 模板语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144698/

相关文章:

css/html 在无序列表中对齐图像上方的文本

python - 如何在 django-tinymce 中启用插件?

python - 使用 ModelForms 时如何更新已存在的行?

python - django查询问题

python - 如何在 Django 表单中添加 truncatechars 过滤器&

html - Div 重叠 : How to push one with position:absolute under the other when they overlap

css - 媒体查询仅适用于 60px

html - 背景渐变结束不继续

python - Django 自定义模型字段 : to_python() not called

django - Django 模板中的嵌套 block