简体   繁体   English

Django模板:对页面使用不同的CSS

[英]Django Templates: Use different css for pages

New to Django, I want to use different css files for different pages - ie page1.css for page1.html, page2.css for page2.html. Django的新手,我想为不同的页面使用不同的css文件 - 例如page1.css用于page1.html,page2.css用于page2.html。 Is there a way to do this while still extending base.html? 有没有办法在扩展base.html的同时做到这一点?

In 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>

In page1.html 在page1.html中

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

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

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

You can use the same concept that applies to {% block content %} in that you can fill it in or extend it on a page by page basis. 您可以使用适用于{% block content %}的相同概念,您可以将其填入或逐页扩展。

Hence, in base.html , create a block called styles in the head section (or anywhere you want to load your CSS): 因此,在base.html ,在head部分(或者你想加载CSS的任何地方)创建一个名为styles的块:

{% block styles %}
{% endblock %}

Now, you can extend this block on a per page basis in any of your templates that use base.html : 现在,您可以在使用base.html任何模板中base.html页扩展此块:

Example: page1/template-view.html 示例: page1/template-view.html

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM