【问题标题】:Django Templates: Use different css for pagesDjango 模板:为页面使用不同的 css
【发布时间】:2014-10-12 18:10:35
【问题描述】:

刚接触 Django,我想为不同的页面使用不同的 css 文件 - 即 page1.css 用于 page1.html,page2.css 用于 page2.html。有没有办法在扩展 base.html 的同时做到这一点?

在base.html中

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>{% block title %}Default Title{% endblock %}</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />

  <!-- css -->
  if page1.html
  <link rel="stylesheet" href="{% static "css/page1.css" %}">

  if page2.html
  <link rel="stylesheet" href="{% static "css/page2.css" %}">

  if page3.html
  <link rel="stylesheet" href="{% static "css/page3.css" %}">

</head>
<body class="{% block body_class %}{% endblock %}">
{% block content %}{% endblock%}
</body>
</html>

在page1.html中

    {% extends "base.html" %}
    {% load staticfiles %}

    {% block body_class %}page1{% endblock %}
    {% block title %}Page1{% endblock %}

    {% block content %}
    Page 1
    {% endblock content %}

【问题讨论】:

    标签: python css django django-templates django-views


    【解决方案1】:

    您可以使用适用于{% block content %} 的相同概念,您可以逐页填写或扩展它。

    因此,在base.html 中,在head 部分(或您要加载CSS 的任何地方)创建一个名为styles 的块:

    {% block styles %}
    {% endblock %}
    

    现在,您可以在任何使用 base.html 的模板中按页面扩展此块:

    示例:page1/template-view.html

    {% extends "base.html" %}
    {% load staticfiles %}
    
    {% block styles %}
        <link rel="stylesheet" href="{% static 'css/page1.css' %}">
    {% endblock %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 2012-11-12
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2020-09-19
      相关资源
      最近更新 更多