Django 模板:为页面使用不同的 css [英] Django Templates: Use different css for pages

查看:24
本文介绍了Django 模板:为页面使用不同的 css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 新手,我想对不同的页面使用不同的 css 文件 - 即 page1.css 用于 page1.html,page2.css 用于 page2.html.有没有办法在扩展 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 中,在 head 部分(或您想要加载 CSS 的任何地方)创建一个名为 styles 的块:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆