Django Templates: Use different css for pages

不打扰是莪最后的温柔 提交于 2019-12-08 21:11:16

问题


New to Django, I want to use different css files for different pages - i.e. page1.css for page1.html, page2.css for page2.html. Is there a way to do this while still extending base.html?

In 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

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

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

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

回答1:


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.

Hence, in base.html, create a block called styles in the head section (or anywhere you want to load your CSS):

{% block styles %}
{% endblock %}

Now, you can extend this block on a per page basis in any of your templates that use base.html:

Example: page1/template-view.html

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

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


来源:https://stackoverflow.com/questions/25386868/django-templates-use-different-css-for-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!