慕课网-Django入门到进阶-更适合Python小白的系统课程-第3章Django中的Template模板-3.3静态文件配置与内置标签代码演示

第3章 Django中的Template模板

3.3 静态文件配置与内置标签代码演示

修改项目

1.在项目中新建目录 static

2.进入项目下目录 template,修改文件 settings.py,添加静态文件路径

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

3.进入项目下目录 app,修改文件 views.py

#coding:utf-8
from django.shortcuts import render
from django.views.generic import View

class Index(View):
    TEMPLATE = 'index.html'

    def get(self, request, name):

        data = {}
        data['name'] = name
        data['array'] = range(10)

        return render(request, self.TEMPLATE, data)

4.进入项目下目录 templates,修改文件 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'index.css' %}">
</head>
<body>
    <h1>hello {{name}}</h1>
    <ul>
        {% for item in array %}
            <li>
                {{item}}--{{ forloop.counter0 }}--{{ forloop.counter }}--{{ forloop.revcounter }}--{{ forloop.revcounter0 }}
                {% if forloop.first %}
                    is first
                {% elif forloop.last %}
                    is last
                {% endif %}
            </li>
            {% empty %}
            <li>is empty</li>
        {% endfor %}
    </ul>
    <a href="{% url 'index' 'conan' %}">return</a>
</body>
</html>

5.进入项目下目录 static,添加文件 index.css

* {
    margin: 0;
    padding: 0;
}

6.测试

7.进入项目下目录 templates,添加文件 base.html,模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
        <meta charset="UTF-8">
        <title>{% block title %}{% endblock %}</title>
        {% block css_style %}
        {% endblock %}
    {% endblock %}
</head>
<body>
    {% block content %}
    {% endblock %}
    {% block js_script %}
    {% endblock %}
</body>
</html>

8.进入项目下目录 templates,修改文件 index.html

{% extends 'base.html' %}
{% load static %}
{% block css_style %}
<link rel="stylesheet" href="{% static 'index.css' %}" />
{% endblock %}
{% block title %}
test
{% endblock %}
{% block content %}
<h1> hello {{name}} </h1>
<ul>
    {% for item in array %}
        <li>{{item}}</li>
    {% endfor %}
</ul>
{% endblock %}

9.测试

posted on 2020-01-17 05:38  herisson_pan  阅读(12)  评论(0)    收藏  举报

导航