如何在 Django 中使用多个样式表,其中样式表由 GET 变量确定,而不违反 DRY?

发布于 2024-10-21 02:16:51 字数 895 浏览 6 评论 0原文

我正在编写一个具有多种皮肤的网站。每个皮肤都有自己的样式表。我希望皮肤由 GET 变量确定,这样这个 URL:

whatever?skin=foo

将导致页面被渲染,在标题中包含这个 HTML:

<link rel="stylesheet" type="text/css" href="/site_media/foo.css"/>

(通常我希望皮肤由用户的偏好确定,但我想要这种方式也是如此,这样用户就可以预览新皮肤的外观,并让我在开发它时变得更容易。)

这在 Django 中相当容易做到,例如您可以使用带有此行的模板:

<link rel="stylesheet" type="text/css" href="/site_media/{{skin}}.css"/>

和这样的视图:

def whateverView(request):
    """ called by URL /whatever """
    skin = request.GET.get('skin', "default")
    c = RequestContext(request, {'skin': skin})
    html = whateverTemplate.render(c)
    return HttpResponse(html)

但我不想这样做,因为我必须向每个视图添加相同的代码,这会违反

那么有什么方法可以做到这一点,使其适用于我的所有页面,同时只编写一次代码?

I an writing a website that will have multiple skins. Each skin has its own style sheet. I would like the skin used to be determined by a GET variable, so that this URL:

whatever?skin=foo

will cause the page to be rendered containing this HTML in the header:

<link rel="stylesheet" type="text/css" href="/site_media/foo.css"/>

(Normally I want the skin to be determined by a user's preference, but I want this way of doing it as well, so a user can preview what a new skin will look like, as well as for making it easy for me while developing it.)

This is fairly easy to do in Django, for example you could use a template with this line:

<link rel="stylesheet" type="text/css" href="/site_media/{{skin}}.css"/>

And a view like this:

def whateverView(request):
    """ called by URL /whatever """
    skin = request.GET.get('skin', "default")
    c = RequestContext(request, {'skin': skin})
    html = whateverTemplate.render(c)
    return HttpResponse(html)

But I don't want to have to do it like that, as I would have to add the same code to every single view, which would violate DRY.

So is there some way I can do it, such that it works on all my pages, while only writing the code once?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最笨的告白 2024-10-28 02:16:51

您可以使用 Django 的上下文处理器来完成此操作: http://docs.djangoproject.com/en/dev/ref/templates/api/?#writing-your-own-context-processors。或者,您可以启用 django.core.conext_processors.request 并访问模板中的请求对象。

You can do this using Django's Context Processors: http://docs.djangoproject.com/en/dev/ref/templates/api/?#writing-your-own-context-processors. Or, you could enable django.core.conext_processors.request and access the request object in your template.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文