开发者

How do I use multiple style sheets in Django, where the style sheet is determined by a GET variable, without violating DRY?

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 HttpRe开发者_JAVA百科sponse(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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜