How to properly extend and include in Django tempa

2019-01-29 11:51发布

问题:

Following is my homepage.html is home app

{% extends "base.html" %}
{% load static %}
<link rel = "stylesheet" href = "{% static 'css/home.css' %}" > #reference to stylesheet in the home app static directory

{% block body %}
   <h1>I am homepage</h1>
{% endblock %}

My base.html in the project root folder is the following

<!DOCTYPE html>
<html>
  <head>
    <link rel = "stylesheet" href = "{% static 'base.css' %}" > #stylesheet in root folder
  </head>

  <body>
     {% block content %}
     {% endblock %}
  </body>
</html>

But here, the home.css in the homepage.html is not functional as the base.html on extend closes the head before the home.css can come in the head section.

Is there any way I can add the CSS into the header

Thanks

回答1:

You just need another block.

In base.html:

<head>
  <link rel="stylesheet" href="{% static 'base.css' %}">
  {% block extrahead %}{% endblock %}
</head>
...

and in homepage.html:

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