【问题标题】:Changing css styles from view in Django在 Django 中从视图中更改 css 样式
【发布时间】:2015-08-18 07:27:04
【问题描述】:

如果对此有明显的答案,请提前抱歉,我仍在学习 Django 的诀窍。

我正在创建一个网站,其中包含 6 个预先确定的主题(未存储在数据库中) 英语、公民、文学、语言、历史、圣经

每个主题都将与一种独特的颜色相关联。

我有一个 subject.html 页面的模板和一个从 url appname/subject/subjectname 加载的视图

我需要做的是根据访问的主题应用特定的 css 来设置页面样式。例如,如果用户转到 appname/subject/english,我希望页面以英语为“主题”。

我希望我已经说清楚了,我也想知道是否有一种方法可以将实际的 css 代码添加到样式表中,而不必从后端逐个更改属性。

非常感谢!

【问题讨论】:

  • 有几种方法可以做到这一点。不同的模板/子模板、模板中的条件、使用 CSS 文件的主题名称并将其传递给您的模板 (<link rel="stylesheet" href="{{ subject }}.css">) 等。这仅取决于您项目的其余部分看起来最简单和最方便。

标签: python html css django


【解决方案1】:

在模板中,您可以使用条件来添加 css,如下所示:

<div class="{% if subject=='civics' %}civic-class{% endif %}"></div>

为此,subject 值应来自 view。 现在,对于主题页面,您可以使用extends 标签。假设:

def your_view(request):
    subject  # Here you get the url subject, 'how' is up to you
    if subject == 'english'
        template_base = '/some/html/tenplate.html'
    elif subject == 'civis':
        template_base = '/some/other/template.html'
    ... # then you return 'template_base' variable to template

然后在模板中:

{% extends template_base %}  # at the top

希望这会有所帮助,如果您使用基于类的视图,这也是同样的逻辑。

【讨论】:

    【解决方案2】:

    Django 的视图不负责演示,它是模板(当然还有 css 等)的责任。现在假设您有相同的视图服务于不同的主题,视图显然需要知道哪个是当前主题(我假设从作为参数传递给视图的 url 的捕获部分),因此它可以轻松地将此信息传递给模板,然后可以使用它将特定于主题的类添加到正文标记。然后你只需要相应地编写你的css。

    举个例子:

    # urls.py
    
    patterns = urlpatterns('',
        #...
        url(r'whatever/(P?<subject>[a-z-]+>)/$', 'myviews.index', ...),
        )
    
    # myviews.py
    def index(request, subject):
        # do whatever
        context = {
           # whatever else
           'subject':subject
           }
       return render(request, "whatever/index.html", context)
    
    # whatever/index.html
    <html>
       # headers etc
       <body class="something {{ subject }} etc">
         # whatever here
       </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      您可以通过多种方式做到这一点。 一般来说,您需要将一些变量从视图返回到 html,并根据此变量选择样式表,如果您的变量名称与样式表的名称匹配,则可以使用 "{{variable}}.css",否则可以使用 JQuery。

      【讨论】:

        猜你喜欢
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 2014-04-29
        • 2013-04-22
        • 1970-01-01
        • 2021-03-31
        • 2021-01-17
        • 2014-08-27
        相关资源
        最近更新 更多