【问题标题】:django template: Is extended template able to change css in parent page?django 模板:扩展模板是否能够更改父页面中的 css?
【发布时间】:2013-01-24 17:35:41
【问题描述】:

我有两个 django 模板页面,其中之一是“base.html”,将基本的 html 标签设置为基本模板。现在我有一个扩展它的页面“child.html”,其中包含{% extends "base.html" %} 之类的内容。现在我必须更改这个特定页面的<body> 背景颜色,所以在“child.html”的 css 中我写道:

body {
    background-color: #000000;
    /* some other css here */
}

但身体似乎对任何变化都没有反应。我想我一定错过了什么。请帮忙,谢谢。

编辑: 在“child.html”中,我只是有

<link rel="stylesheet" type="text/css" href="/site-media/css/template_conf.css"/>

我尝试在template_conf.css 中更改body css,并且没有其他页面包含template_conf.css

【问题讨论】:

  • 在“child.html”的 css 中是什么意思?该 CSS 是如何包含在模板中的?
  • @DanielRoseman:我更新了问题。感谢您的帮助。
  • link标签是否包含在由父级定义的模板块中,所以它实际上被渲染了?它是否出现在呈现的 HTML 中?

标签: django templates extend


【解决方案1】:

在主模板中:

<body class="{% block body_class %}{% endblock %}">
...
</body>

然后在子模板中,定义块即可:

{% block body_class %} my_new_body_css_class {% endblock %}

这将呈现&lt;body class="my_new_body_css_class"&gt;...&lt;/body&gt;,您必须在链接的 CSS 中定义此类。

【讨论】:

    【解决方案2】:

    为此,请在头部的 base.html 中添加一个块,允许您在 base.html 中的那个之后插入另一个 css

    <head>
    
        .... other head tags ....
    
        <link rel="stylesheet" type="text/css" href="/site-media/css/template_conf.css"/>
        {% block extra_css %}{% endblock %}
    </head>
    

    这允许您通过在 child.html 中添加另一个 &lt;link&gt; 标记来覆盖 template_conf.css 中的 css 标记

    {% block extra_css %}
    <link rel="stylesheet" type="text/css" href="/site-media/css/child_template.css"/>
    {% endblock %}
    

    这允许您覆盖 base.html 中需要更改的部分,同时仍然能够调整 child.html 中所需的页面部分。

    【讨论】:

    • 有趣。我想知道哪个是理想的方法。这个或@ablm 建议的那个。有什么想法吗?
    【解决方案3】:

    如果你看到在 firebug 或其他浏览器调试器中加载了新的 css, 请尝试:

    body {
    background-color: #000000 !important;
    /* some other css here */
    

    }

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 2017-04-24
      • 2012-01-10
      • 2011-10-14
      • 2015-03-03
      • 2010-11-27
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多