在CSS档案中使用Django范本语法 [英] Use Django template syntax in a css file

查看:78
本文介绍了在CSS档案中使用Django范本语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a css file home_global.css which has the following in it:

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

此静态文件的加载方式为:

This static file is loaded using:

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

但是,预期背景图片的网址无法解析,但会按字面意义进行解析.我想做的是在css文件中启用Django模板语法.

However the url of the background-image, expectedly, doesn't resolve but is parsed literally. What I would like to do is enable Django template syntax in the css file.

请注意,静态网址等均已正确设置,并且该问题不涉及此问题.

Please note that the static URLs etc are all set up correctly and this question doesn't involve that.

这个问题与我一个月前问过的另一个问题非常相似: 如何在静态文件中使用django模板语法

This question is very similar to another question that I myself asked a month ago: How to use django template syntax in static files

但是,这里提供的答案是 javascript 所特有的,并且特别指出:阻止此问题的基本问题是将上下文传递给render()函数中提到的模板在视图(或任何其他函数中,其行为方式相同,例如render_to-response())."

However, the answer provided there was specific to javascript, and in particular noted that "The fundamental issue that prevents this is that context is passed to the template that is mentioned in your render() function in the view(or any other function the behaves the same way e.g. render_to-response())."

如果我正确理解这一点,则此处不存在相同的限制.此外,我随后从Django文档中了解到可以在各种文本文档中使用Django模板语法.因此,在我看来,在 this 情况下,我想在css文件中使用它,这应该是可能的.那么,我该怎么办呢?

If I understand this correctly, the same limitation does not apply here. Furthermore, I've subsequently learned from the Django documentation that it is possible to use Django template syntax in a variety of text documents. It therefore seems to me that in this case, where I want to use it in a css file, this should be possible. So, how can I do this?

推荐答案

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

As you correctly pointed out, Django templates can be used for any text file, not just HTML. However, you need to make sure they're rendered by the template engine, providing a specific url and a view.

这样,您可以期望对所有变量和标签进行插值,尤其是用settings.STATIC_URL替换静态". 但是,我不会坚持在CSS文件本身的URL前面加上"/static/" ...这可能会骗人,因为您宁愿动态呈现文件.

That way, you can expect to have all variables and tags interpolated, and in particular to have "static" replaced by settings.STATIC_URL. However, I wouldn't insist in prepending "/static/" to the url of the CSS file itself ... that would be cheating, as you're rather rendering the file dynamically.

在实践中:

project/urls.py

project/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')
    ),
    ...
]

该视图相当琐碎,并已内联到urls.py中. 请注意,我还指定了适当的模仿类型'text/css'.

The view is rather trivial, and has been inlined in urls.py. Please note I also specified the appropriate mimetype 'text/css'.

在这里,我在URL前面添加了一个'css/'前缀,但这不是必需的,并且您的项目中不需要"css"文件夹; 只要确保模板引擎可以找到"home_global.css"即可;也就是说,将其放在所有已安装应用程序的/template/子文件夹中, 甚至在项目中(如果已列出已安装的应用程序中的项目):

Here, I prepended a 'css/' prefix to the url, but this is not necessary, and you don't need a "css" folder in your project; just make sure that the template engine can find "home_global.css"; that is, put it in the /template/ subfolder of any installed app, or even in the project if it is listed among the installed apps:

project/templates/home_global.css

project/templates/home_global.css

{% load static %}

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

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

You can check immediately the result by navigating to this url with your browser:

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

呈现文档如下:

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

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

and include it in main template as required:

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

是否需要渲染多个CSS文档,将文件名作为参数,然后对所有文档使用单个视图可能会很方便.在这种情况下,为简单起见,我将选择基于函数的视图:

Should you need to render many css documents, it might be convenient to treat the filename as parameter, then use a single view for all documents. In this case I would opt for a function based view, for simplicity:

urls.py:

from django.urls import path
from . import views

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

其中:

views.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档案中使用Django范本语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆