问题描述
Django的新功能,我想为不同的页面使用不同的CSS文件,例如page1.html的page1.css,page2.html的page2.css。有没有办法在继续扩展base.html?
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?
在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>
在page1.html
In page1.html
{% extends "base.html" %}
{% load staticfiles %}
{% block body_class %}page1{% endblock %}
{% block title %}Page1{% endblock %}
{% block content %}
Page 1
{% endblock content %}
推荐答案
您可以使用适用于 {%block 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.
因此在 base.html
中,在头中创建一个名为
部分(或任何你要加载CSS的地方): style
的块
Hence, in base.html
, create a block called styles
in the head
section (or anywhere you want to load your CSS):
{% block styles %}
{% endblock %}
现在,您可以在任何模板中按每页扩展此块使用 base.html
:
Now, you can extend this block on a per page basis in any of your templates that use base.html
:
示例: page1 / template-view.html
{% extends "base.html" %}
{% load staticfiles %}
{% block styles %}
<link rel="stylesheet" href="{% static 'css/page1.css' %}">
{% endblock %}
这篇关于Django模板:对页面使用不同的CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!