0004.Django Template之模板标签

网页强制刷新:ctrl+F5

常用标签

模板标签作用,可以在模板中进行各种逻辑操作,比如,循环、判断等

1. 语法

{% load static %}        #加载第三方标签

{% tag %}[{% endtag%}]

{% for student in students %} 项目{% endfor %}

{% if student.sex == ‘女’ %} 项目{% endif %}

urls.py代码

from django.urls import path, re_path
from . import views

app_name = 'teacher'

urlpatterns = [
    path('index/', views.index, name='index'),   #对url进行命名,在url变更后保持name不变,通过reverse仍然可以访问index
    path('login/', views.login),
    path('detail/<name>/', views.detail, name='detail')
]

views.py代码

from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from datetime import datetime


def index(request):
    now = datetime.now()
    #now = now.strftime('%Y年%m月%d日 %H:%M:%S')  #对时间呈现方式进行格式化
    lt = [1, 2, 3]
    dt = {'name': 'tiger', 'age': 18}
    js = '<script>alert("1")</script>'
    html = '<h1>我是安全的</h1>'
    students =[
        {'name':'tager', 'age':18, 'sex':''},
        {'name': 'liuda', 'age': 19, 'sex': ''},
        {'name': 'lier', 'age': 20, 'sex': ''},
        {'name': 'zhangsan', 'age': 18, 'sex': ''},
        {'name': 'wangwu', 'age': 21, 'sex': ''},
    ]

    def func():
        return '函数'
    return render(request, 'teacher/index.html', context={
        'now': now,
        'lt': lt,
        'dt': dt,
        'func': func,
        'js': js,
        'html': html,
        'students': students,
    })

def login(request):
    # return redirect('https://www.baidu.com')
    # return  redirect(('/student/index/')) #硬编码,在url变化后,就无法访问
    # url = reverse('teacher:index')
    # return redirect(url)
    return render(request, 'teacher/login.html')

def detail(request, name):
    return HttpResponse(f'这是{name}同学的详情!')

HTML代码

{% load static %}  <!--#此处导入static后,将不再调用setting文件中的STATIC_URL = '/static/',直接调用STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {# <link rel="stylesheet" href="/static/teacher/index.css"> #}
    <link rel="stylesheet" href="{% static 'teacher/index.css' %}">  <!--#此处搭配首行一起使用-->
    <title>首页面</title>
</head>
<body>
    <h1 style="color:red">我是teacher App下的首页面</h1>
    <p>现在的时间:{{ now }}</p>
    <p>现在的时间:{{ now|date:'Y年m月d日 H:i:s' }}</p>  <!--HTML文件对输出的格式化-->
    <p>我是一个列表:{{ lt }}</p>
    <p>我是一个列表的第一个值:{{ lt.0 }}</p>
    <p>我是一个列表的第一个值first:{{ lt|first }}</p>
    <p>值的操作:{{ lt.0|add:2|add:lt.2 }}</p>
    <p>值的操作:{{ lt.0|add:2|add:lt.2|add:'a'|default:'nothing' }}</p> <!--在出现无法相加情况下,采用default给定输出-->
    <p>我是一个字典:{{ dt }}</p>
    <p>我是一个字典中某个key的值:{{ dt.name }}</p>
    <p>我是一个字典中item:{{ dt.items }}</p>
    <p>我是一个函数:{{ func }}</p>
    <p>我是脚本代码:{{ js }}</p>
    <p>我是脚本代码:{{ js|safe }}</p>
    <p>我是html代码:{{ html }}</p>
    <p>我是html代码:{{ html|safe }}</p>  <!--确认代码安全-->
    {#  <p>{{ students }}</p>  #}
    <!--table>tr*5>td*4+tab键,即可生成对应的5行4列表格-->
    <table>
        <tr>
            <td>序号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
        <tr>
            <td>1</td>
            <td>{{ students.0.name }}</td>
            <td>{{ students.0.age }}</td>
            <td>{{ students.0.sex }}</td>
        </tr>
        <tr>
            <td>2</td>
            <td>{{ students.1.name }}</td>
            <td>{{ students.1.age }}</td>
            <td>{{ students.1.sex }}</td>
        </tr>
        <tr>
            <td>3</td>
            <td>{{ students.2.name }}</td>
            <td>{{ students.2.age }}</td>
            <td>{{ students.2.sex }}</td>
        </tr>
        <tr>
            <td>4</td>
            <td>{{ students.3.name }}</td>
            <td>{{ students.3.age }}</td>
            <td>{{ students.3.sex }}</td>
        </tr>
    </table>
    <table>
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        {% for student in students %}
        <tr {% if student.sex == '女' %}style="color:red;"{% endif %}>
            <td><a href="{% url 'teacher:detail' student.name %}">{{ forloop.counter }}</a></td>  <!-- forloop.counter0从0开始计数,没有0则从1开始计数-->
            <td>{{ student.name }}</td>
            <td>{{ student.age }}</td>
            <td>{{ student.sex }}</td>
        </tr>
        {% endfor %}
    </table>
</body>

</html>

模板的继承与引用

1. 引用include

1 {% include ‘teacher/ad.html’ %}

2 作用:在模板文件的某个特定的位置引入另一个模板的内容

{% load static %}  <!--#此处导入static后,将不再调用setting文件中的STATIC_URL = '/static/',直接调用STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {# <link rel="stylesheet" href="/static/teacher/index.css"> #}
    <link rel="stylesheet" href="{% static 'teacher/index.css' %}">  <!--#此处搭配首行一起使用-->
    <title>首页面</title>
</head>
<body>
    <h1 style="color:red">我是teacher App下的首页面</h1>
    <p>现在的时间:{{ now }}</p>
    <p>现在的时间:{{ now|date:'Y年m月d日 H:i:s' }}</p>  <!--HTML文件对输出的格式化-->
    <p>我是一个列表:{{ lt }}</p>
    <p>我是一个列表的第一个值:{{ lt.0 }}</p>
    <p>我是一个列表的第一个值first:{{ lt|first }}</p>
    <p>值的操作:{{ lt.0|add:2|add:lt.2 }}</p>
    <p>值的操作:{{ lt.0|add:2|add:lt.2|add:'a'|default:'nothing' }}</p> <!--在出现无法相加情况下,采用default给定输出-->
    <p>我是一个字典:{{ dt }}</p>
    <p>我是一个字典中某个key的值:{{ dt.name }}</p>
    <p>我是一个字典中item:{{ dt.items }}</p>
    <p>我是一个函数:{{ func }}</p>
    <p>我是脚本代码:{{ js }}</p>
    <!--<p>我是脚本代码:{{ js|safe }}</p>-->
    <p>我是html代码:{{ html }}</p>
    <!--<p>我是html代码:{{ html|safe }}</p>-->  <!--确认代码安全-->
    {#  <p>{{ students }}</p>  #}
    <!--table>tr*5>td*4+tab键,即可生成对应的5行4列表格-->
    <table>
        <tr>
            <td>序号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
        <tr>
            <td>1</td>
            <td>{{ students.0.name }}</td>
            <td>{{ students.0.age }}</td>
            <td>{{ students.0.sex }}</td>
        </tr>
        <tr>
            <td>2</td>
            <td>{{ students.1.name }}</td>
            <td>{{ students.1.age }}</td>
            <td>{{ students.1.sex }}</td>
        </tr>
        <tr>
            <td>3</td>
            <td>{{ students.2.name }}</td>
            <td>{{ students.2.age }}</td>
            <td>{{ students.2.sex }}</td>
        </tr>
        <tr>
            <td>4</td>
            <td>{{ students.3.name }}</td>
            <td>{{ students.3.age }}</td>
            <td>{{ students.3.sex }}</td>
        </tr>
    </table>
    <table>
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        {% for student in students %}
        <tr {% if student.sex == '女' %}style="color:red;"{% endif %}>
            <td><a href="{% url 'teacher:detail' student.name %}">{{ forloop.counter }}</a></td>  <!-- forloop.counter0从0开始计数,没有0则从1开始计数-->
            <td>{{ student.name }}</td>
            <td>{{ student.age }}</td>
            <td>{{ student.sex }}</td>
        </tr>
        {% endfor %}
    </table>
    <div id="ad" style="position:fixed;bottom:0;right:0;border:1px solid red;height:200px;width:200px;background-color:red;">
        {% include 'teacher/ad.html' %}
    </div>
</body>

</html>

ad.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我是广告!</title>
</head>
<body>
    <h3>这是一段植入广告!</h3>
</body>
</html>

2. 继承extends&block

开发一个网站,页面间有很多相同的部分。

解决方法:不同页面相同部分抽离起来

{% extends ‘teacher/base.html’ %}   #放在最前面

语法:

  {% block blockname %}

  {% endblock %}

示例:

  {% block title %}

    <title>登录界面</tilte>

  {% endblock %}

1.
<title>{% block title %}Bootstrap, from Twitter{% endblock %}</title>

<!--调用-->
{% block title %}
    首页面
{% endblock %}

2.
{% block title %}<title>Bootstrap, from Twitter</title>{% endblock %}
<!--调用-->
{% block title %}
    <title>首页面</title>
{% endblock %}

base.html代码

{% load static %}   <!--导入第三方模板-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    {% block title %}<title>Bootstrap, from Twitter</title>{% endblock %}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->
    <link rel="stylesheet" href="{% static 'teacher/bootstrap.css' %}">
    {% block link %}{% endblock %}
    <style>
      body {
        padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
      }
    </style>
{% block style %}
<style type="text/css">
      body {
        padding-top: 40px;
        padding-bottom: 40px;
        background-color: #f5f5f5;
      }

      .form-signin {
        max-width: 300px;
        padding: 19px 29px 29px;
        margin: 0 auto 20px;
        background-color: #fff;
        border: 1px solid #e5e5e5;
        -webkit-border-radius: 5px;
           -moz-border-radius: 5px;
                border-radius: 5px;
        -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
           -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
                box-shadow: 0 1px 2px rgba(0,0,0,.05);
      }
      .form-signin .form-signin-heading,
      .form-signin .checkbox {
        margin-bottom: 10px;
      }
      .form-signin input[type="text"],
      .form-signin input[type="password"] {
        font-size: 16px;
        height: auto;
        margin-bottom: 15px;
        padding: 7px 9px;
      }

    </style>
{% endblock %}
    {# <link href="../assets/css/bootstrap-responsive.css" rel="stylesheet"> #}
    <link rel="stylesheet" href="{% static 'teacher/responsesive.css' %}">
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="../assets/js/html5shiv.js"></script>
    <![endif]-->

    <!-- Fav and touch icons -->
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
                    <link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
                                   <link rel="shortcut icon" href="../assets/ico/favicon.png">
  </head>

  <body>

    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="brand" href="#">Project name</a>
          <div class="nav-collapse collapse">
            <ul class="nav">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="#about">About</a></li>
              <li><a href="#contact">Contact</a></li>
            </ul>
          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>

    {% block content %}
    {% endblock %}

    <div class="container">

      <h1>Bootstrap starter template</h1>
      <p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>

    </div> <!-- /container -->

    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="../assets/js/jquery.js"></script>
    <script src="../assets/js/bootstrap-transition.js"></script>
    <script src="../assets/js/bootstrap-alert.js"></script>
    <script src="../assets/js/bootstrap-modal.js"></script>
    <script src="../assets/js/bootstrap-dropdown.js"></script>
    <script src="../assets/js/bootstrap-scrollspy.js"></script>
    <script src="../assets/js/bootstrap-tab.js"></script>
    <script src="../assets/js/bootstrap-tooltip.js"></script>
    <script src="../assets/js/bootstrap-popover.js"></script>
    <script src="../assets/js/bootstrap-button.js"></script>
    <script src="../assets/js/bootstrap-collapse.js"></script>
    <script src="../assets/js/bootstrap-carousel.js"></script>
    <script src="../assets/js/bootstrap-typeahead.js"></script>

  </body>
</html>

index.html代码   对base.html的继承调用

{% extends 'teacher/base.html' %}  <!--当前模板继承父模板base.html-->
{% load static %}  <!--#此处导入static后,将不再调用setting文件中的STATIC_URL = '/static/',直接调用STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -->
{% block title %}
    <title>首页面</title>
{% endblock %}
{% block link %}
    <link rel="stylesheet" href="{% static 'teacher/index.css' %}">
{% endblock %}
{% block content %}
    <table>
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        {% for student in students %}
        <tr {% if student.sex == '女' %}style="color:red;"{% endif %}>
            <td><a href="{% url 'teacher:detail' student.name %}">{{ forloop.counter }}</a></td>  <!-- forloop.counter0从0开始计数,没有0则从1开始计数-->
            <td>{{ student.name }}</td>
            <td>{{ student.age }}</td>
            <td>{{ student.sex }}</td>
        </tr>
        {% endfor %}
    </table>
{% endblock %}

login.html代码  对base.html的继承调用

{% extends 'teacher/base.html' %}
{% load static %}
{% block title %}
    <title>登录界面</title>
{% endblock %}
{% block link %}
    <link rel="stylesheet" href="{% static 'teacher/login.css' %}">
{% endblock %}
{% block style %}
    <style type="text/css">
      body {
        padding-top: 40px;
        padding-bottom: 40px;
        background-color: #f5f5f5;
      }

      .form-signin {
        max-width: 300px;
        padding: 19px 29px 29px;
        margin: 0 auto 20px;
        background-color: #fff;
        border: 1px solid #e5e5e5;
        -webkit-border-radius: 5px;
           -moz-border-radius: 5px;
                border-radius: 5px;
        -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
           -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
                box-shadow: 0 1px 2px rgba(0,0,0,.05);
      }
      .form-signin .form-signin-heading,
      .form-signin .checkbox {
        margin-bottom: 10px;
      }
      .form-signin input[type="text"],
      .form-signin input[type="password"] {
        font-size: 16px;
        height: auto;
        margin-bottom: 15px;
        padding: 7px 9px;
      }
    </style>
{% endblock %}
{% block content %}
    <div class="container">

      <form class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>
        <input type="text" class="input-block-level" placeholder="Email address">
        <input type="password" class="input-block-level" placeholder="Password">
        <label class="checkbox">
          <input type="checkbox" value="remember-me"> Remember me
        </label>
        <button class="btn btn-large btn-primary" type="submit">Sign in</button>
      </form>

    </div>
{% endblock %}

 

原文地址:http://www.cnblogs.com/lxinghua/p/16852721.html

发表评论

您的电子邮箱地址不会被公开。