如何使用动态CSS渲染模板? [英] How to render a template with dynamic CSS?

查看:234
本文介绍了如何使用动态CSS渲染模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在视图中创建一个动态CSS文件,然后呈现一个加载该CSS文件的模板.根据提供给视图的参数,每次调用视图时,CSS在某些位置可能具有不同的值.我将如何去做? (我应该补充一点,我没有使用Python/Django编写文件的经验.)

I want to create a dynamic CSS file in a view and then render a template which loads that CSS file. Depending on the arguments given to the view, the CSS may have different values at certain places every time the view is called. How would I go about doing that? (I should add that I have no experience with writing files in Python/Django.)

以下是我认为应如何工作的简化示例:

Here is a simplified example of how I think it should work:

# urls.py
urlpatterns = patterns('',
    (r'^myview/(?P<color>[0-9a-f]{6})/$', create_css_file),
)

# views.py
def create_css_file(request, color):
    raw = "@charset 'UTF-8';\n\n"
    raw += "body {\n"
    raw += "  color: #" + color + ";\n"
    raw += "}\n\n"

    f = open('mydynamic.css', 'r+')
    f.write(raw)

    return render_to_response('mytemplate.html', locals())

# mytemplate.html
{% extends "base.html" %}
{% block head %}
    <link rel="stylesheet" media="screen" href="{{ f.name }}" />
{% endblock %}

由于某种原因,这不起作用,尽管在生成的HTML页面的源代码中,看起来CSS文件已正确加载. f甚至可以正确到达模板,因为将<link>...行更改为

For some reason, that doesn't work, although in the resulting HTML page's source code, it looks like the CSS file is loaded correctly. The f even arrives at the template correctly, because I can see its contents when I change the <link>... line to

<link rel="stylesheet" media="screen" href="{{ f }}" />

(f代替f.name).但是HTML呈现时没有所需的颜色设置.谁能告诉我为什么呢?

(finstead of f.name). But the HTML is rendered without the desired color setting. Can anybody tell my why that is?

我怀疑存在路径问题,并且在很多地方使用不同的路径开玩笑,但无济于事.

I suspected some path issue, and I toyed around quite a bit with different paths, but to no avail.

请不要建议我准备几个硬编码的CSS文件(正如我在类似问题的答案中所发现的那样),因为有数百种可能性.

Please do not advise me to prepare several hardcoded CSS files (as I have found in answers to similar questions), because there will be several hundred possibilities.

推荐答案

我接受@CatPlusPlus的建议:计算视图中的必要值,并将包含整个CSS的非常长的字符串(raw)传递给模板.在模板中,我像这样包含它:

I went with @CatPlusPlus's suggestion: Calculating the necessary values in a view and passing the template a very long string (raw) which contains the entire CSS. In the template, I include it like so:

<style media="screen">{{ raw|safe }}</style>

感谢大家的努力!

这篇关于如何使用动态CSS渲染模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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