Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Templates: Use different css for pages

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 %}
like image 728
cusejuice Avatar asked Aug 19 '14 15:08

cusejuice


1 Answers

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 %}
like image 103
jrd1 Avatar answered Oct 19 '22 22:10

jrd1