• Django模板层


    模板之变量

    1. 所有的数据类型都可以在模板中使用
    2. render(request, 'index.html', context={''})
    3. render(request, 'index.html', context=locals())
    4. """在模板中使用变量的时候,用的是字典的key值,key值value值一般保持一致"""
    5. 详细请看上一篇末尾

    模版之过滤器

    语法

    1. {{obj|filter__name:param}} 变量名字|过滤器名称:变量

    类似于函数,函数才可以传递参数
    语法:
        {{ obj|过滤器:参数 }}
    过滤器:
        default
        length
        filesizeformat
        date
        trancatechars
        slice
        safe
        mark_safe # 导入

    default

    如果一个变量是false或者为空,使用给定的默认值。否则,使用变量的值。例如:

    1. {{ value|default:"nothing"}}

    length

    返回值的长度。它对字符串和列表都起作用。例如:

    1. {{ value|length }}

    如果 value 是 [‘a’, ‘b’, ‘c’, ‘d’],那么输出是 4。

    filesizeformat

    将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB', '4.1 MB', '102 bytes', 等等)。例如:

    1. {{ value|filesizeformat }}

    如果 value 是 123456789,输出将会是 117.7 MB。

    date

    如果 value=datetime.datetime.now()

    1. {{ value|date:"Y-m-d"}}

    slice

    如果 value=”hello world”

    1. {{ value|slice:"2:-1"}}

    truncatechars

    如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“…”)结尾。

    参数:要截断的字符数

    例如:

    1. {{ value|truncatechars:9}}

    safe

    Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。比如:

    value="<a href="">点击a>"
    
    1. {{ value|safe}}
    2. from django.utils.safestring import mark_safe
    3. res = mark_safe('<h1>HELLO WORLDh1>')

    其它过滤器(了解)

    过滤器

    描述

    示例

    upper

    以大写方式输出

    add

    给value加上一个数值

    addslashes

    单引号加上转义号

    capfirst

    第一个字母大写

    center

    输出指定长度的字符串,把变量居中

    cut

    删除指定字符串

    date

    格式化日期

    default

    如果值不存在,则使用默认值代替

    default_if_none

    如果值为None, 则使用默认值代替

    dictsort

    按某字段排序,变量必须是一个dictionary

    dictsortreversed

    按某字段倒序排序,变量必须是dictionary

    divisibleby

    判断是否可以被数字整除

    escape

    按HTML转义,比如将”<”转换为”<”

    filesizeformat

    增加数字的可读性,转换结果为13KB,89MB,3Bytes等

    first

    返回列表的第1个元素,变量必须是一个列表

    floatformat

    转换为指定精度的小数,默认保留1位小数

    get_digit

    从个位数开始截取指定位置的数字

    join

    用指定分隔符连接列表

    length

    返回列表中元素的个数或字符串长度

    length_is

    检查列表,字符串长度是否符合指定的值

    linebreaks


    标签包裹变量

    linebreaksbr


    标签代替换行符

    linenumbers

    为变量中的每一行加上行号

    ljust

    输出指定长度的字符串,变量左对齐

    lower

    字符串变小写

    make_list

    将字符串转换为列表

    pluralize

    根据数字确定是否输出英文复数符号

    random

    返回列表的随机一项

    removetags

    删除字符串中指定的HTML标记

    rjust

    输出指定长度的字符串,变量右对齐

    slice

    切片操作, 返回列表

    slugify

    在字符串中留下减号和下划线,其它符号删除,空格用减号替换

    stringformat

    字符串格式化,语法同python

    time

    返回日期的时间部分

    timesince

    以“到现在为止过了多长时间”显示时间变量

    timeuntil

    以“从现在开始到时间变量”还有多长时间显示时间变量

    title

    每个单词首字母大写

    truncatewords

    将字符串转换为省略表达方式

    truncatewords_html

    同上,但保留其中的HTML标签

    urlencode

    将字符串中的特殊字符转换为url兼容表达方式

    urlize

    将变量字符串中的url由纯文本变为链接

    wordcount

    返回变量字符串中的单词数

     模版之标签

    标签看起来像是这样的: {% tag %}
    标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模版中。
    一些标签需要开始和结束标签 (例如{% tag %} ...标签 内容 ... {% endtag %}

    for标签

    遍历每一个元素:

    1. {% for person in person_list %}
    2. {{ person.name }}

    3. {% endfor %}
    4. #可以利用{% for obj in list reversed %}反向完成循环。

    遍历一个字典:

    1. {% for key,val in dic.items %}
    2. <p>{{ key }}:{{ val }}p>
    3. {% endfor %}
    4. {% for foo in d.keys %}
    5. <p>{{ foo }}p>
    6. {% endfor %}
    7. {% for foo in d.values %}
    8. <p>{{ foo }}p>
    9. {% endfor %}
    10. {% for foo in d.items %}
    11. <p>{{ foo }}p>
    12. {% endfor %}

    注:循环序号可以通过{{forloop}}显示

    1. forloop.counter The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始)
    2. forloop.counter0 The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始)
    3. forloop.revcounter The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始)
    4. forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始)
    5. forloop.first True if this is the first time through the loop 当前循环是不是第一次循环(布尔值)
    6. forloop.last True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值)
    7. forloop.parentloop 本层循环的外层循环

    for … empty

    1. # for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。
    2. {% for person in person_list %}
    3. <p>{{ person.name }}</p>
    4. {% empty %}
    5. <p>sorry,no person here</p>
    6. {% endfor %}

    if 标签

    1. # {% if %}会对一个变量求值,如果它的值是True(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。
    2. {% if num > 100 or num < 0 %}
    3. <p>无效</p>
    4. {% elif num > 80 and num < 100 %}
    5. <p>优秀</p>
    6. {% else %}
    7. <p>凑活吧</p>
    8. {% endif %}
    9. if语句支持 andor==><、!=<=>=innot inisis not判断。

    with

    使用一个简单地名字缓存一个复杂的变量,当你需要使用一个“昂贵的”方法(比如访问数据库)很多次的时候是非常有用的

    例如:

    1. d = {'username':'kevin','age':18,'info':'这个人有点意思','hobby':[111,222,333,{'info':'NB'}]}
    2. # with起别名
    3. {% with d.hobby.3.info as nb %}
    4. <p>{{ nb }}</p>
    5. with语法内就可以通过as后面的别名快速的使用到前面非常复杂获取数据的方式
    6. <p>{{ d.hobby.3.info }}</p>
    7. {% endwith %}
    8. {% with total=business.employees.count %}
    9. {{ total }} employee{{ total|pluralize }}
    10. {% endwith %}
    11. 不要写成as

    csrf_token

    {% csrf_token%}
    

    这个标签用于跨站请求伪造保护

     模版导入和继承

    模版导入

    1. 语法:{% include '模版名称' %}
    2.   如:{% include 'adv.html' %}

     基本代码示例

    1. <div class="adv">
    2. <div class="panel panel-default">
    3. <div class="panel-heading">
    4. <h3 class="panel-title">Panel title</h3>
    5. </div>
    6. <div class="panel-body">
    7. Panel content
    8. </div>
    9. </div>
    10. <div class="panel panel-danger">
    11. <div class="panel-heading">
    12. <h3 class="panel-title">Panel title</h3>
    13. </div>
    14. <div class="panel-body">
    15. Panel content
    16. </div>
    17. </div>
    18. <div class="panel panel-warning">
    19. <div class="panel-heading">
    20. <h3 class="panel-title">Panel title</h3>
    21. </div>
    22. <div class="panel-body">
    23. Panel content
    24. </div>
    25. </div>
    26. </div>
    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    7. {# <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">#}
    8. <style>
    9. * {
    10. margin: 0;
    11. padding: 0;
    12. }
    13. .header {
    14. height: 50px;
    15. width: 100%;
    16. background-color: #369;
    17. }
    18. </style>
    19. </head>
    20. <body>
    21. <div class="header"></div>
    22. <div class="container">
    23. <div class="row">
    24. <div class="col-md-3">
    25. {% include 'adv.html' %}
    26. </div>
    27. <div class="col-md-9">
    28. {% block conn %}
    29. <h1>你好</h1>
    30. {% endblock %}
    31. </div>
    32. </div>
    33. </div>
    34. </body>
    35. </html>
    1. {% extends 'base.html' %}
    2. {% block conn %}
    3. {{ block.super }}
    4. 是啊
    5. {% endblock conn%}

     模版继承

    Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让您创建一个基本的“骨架”模版,它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 blocks 。

    通过从下面这个例子开始,可以容易的理解模版继承:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <link rel="stylesheet" href="style.css"/>
    5. <title>{% block title %}My amazing site{% endblock %}</title>
    6. </head>
    7. <body>
    8. <div id="sidebar">
    9. {% block sidebar %}
    10. <ul>
    11. <li><a href="/">Home</a></li>
    12. <li><a href="/blog/">Blog</a></li>
    13. </ul>
    14. {% endblock %}
    15. </div>
    16. <div id="content">
    17. {% block content %}{% endblock %}
    18. </div>
    19. </body>
    20. </html>

    这个模版,我们把它叫作 base.html, 它定义了一个可以用于两列排版页面的简单HTML骨架。“子模版”的工作是用它们的内容填充空的blocks。

    在这个例子中, block 标签定义了三个可以被子模版内容填充的block。 block 告诉模版引擎: 子模版可能会覆盖掉模版中的这些位置。

    子模版可能看起来是这样的:

    1. {% extends "base.html" %}
    2. {% block title %}My amazing blog{% endblock %}
    3. {% block content %}
    4. {% for entry in blog_entries %}
    5. <h2>{{ entry.title }}</h2>
    6. <p>{{ entry.body }}</p>
    7. {% endfor %}
    8. {% endblock %}

    extends 标签是这里的关键。它告诉模版引擎,这个模版“继承”了另一个模版。当模版系统处理这个模版时,首先,它将定位父模版——在此例中,就是“base.html”。

    那时,模版引擎将注意到 base.html 中的三个 block 标签,并用子模版中的内容来替换这些block。根据 blog_entries 的值,输出可能看起来是这样的:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <link rel="stylesheet" href="style.css" />
    5. <title>My amazing blog</title>
    6. </head>
    7. <body>
    8. <div id="sidebar">
    9. <ul>
    10. <li><a href="/">Home</a></li>
    11. <li><a href="/blog/">Blog</a></li>
    12. </ul>
    13. </div>
    14. <div id="content">
    15. <h2>Entry one</h2>
    16. <p>This is my first entry.</p>
    17. <h2>Entry two</h2>
    18. <p>This is my second entry.</p>
    19. </div>
    20. </body>
    21. </html>

    请注意,子模版并没有定义 `sidebar` block,所以系统使用了父模版中的值。父模版的 `{% block %}` 标签中的内容总是被用作备选内容(fallback)。

    这种方式使代码得到最大程度的复用,并且使得添加内容到共享的内容区域更加简单,例如,部分范围内的导航。

    **这里是使用继承的一些提示**:

    如果你在模版中使用 `{% extends %}` 标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作。

    在base模版中设置越多的 `{% block %}` 标签越好。请记住,子模版不必定义全部父模版中的blocks,所以,你可以在大多数blocks中填充合理的默认内容,然后,只定义你需要的那一个。多一点钩子总比少一点好。

    如果你发现你自己在大量的模版中复制内容,那可能意味着你应该把内容移动到父模版中的一个 `{% block %}` 中。

    If you need to get the content of the block from the parent template, the `{{ block.super }}` variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using `{{ block.super }}` will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template.

    为了更好的可读性,你也可以给你的 `{% endblock %}` 标签一个 *名字* 。例如:
     {%block content %}...{%endblock content %}



     在大型模版中,这个方法帮你清楚的看到哪一个  `{% block %}` 标签被关闭了。
    不能在一个模版中定义多个相同名字的 `block` 标签。

    实战代码实例

    Bootstrap中文网获取模块

     

    导航条

    巨幕

    缩略图

    views.py模块

    1. def home(request):
    2. return render(request,'home.html')
    3. def login(request):
    4. return render(request,'login.html')
    5. def register(request):
    6. return render(request,'register.html')

     urls.py模块

    1. from django.conf.urls import url
    2. from django.contrib import admin
    3. from app01 import views
    4. urlpatterns = [
    5. url(r'^admin/', admin.site.urls),
    6. url(r'^index/',views.index),
    7. url(r'^home/',views.home),
    8. url(r'^login/',views.login),
    9. url(r'^register/',views.register),
    10. ]

    templates\home.html模块

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    7. <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    8. <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    9. {% block css %}
    10. {% endblock %}
    11. </head>
    12. <body>
    13. <nav class="navbar navbar-default">
    14. <div class="container-fluid">
    15. <!-- Brand and toggle get grouped for better mobile display -->
    16. <div class="navbar-header">
    17. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
    18. data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    19. <span class="sr-only">Toggle navigation</span>
    20. <span class="icon-bar"></span>
    21. <span class="icon-bar"></span>
    22. <span class="icon-bar"></span>
    23. </button>
    24. <a class="navbar-brand" href="#">《遮天》</a>
    25. </div>
    26. <!-- Collect the nav links, forms, and other content for toggling -->
    27. <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    28. <ul class="nav navbar-nav">
    29. <li class="active"><a href="#">荒古圣体<span class="sr-only">(current)</span></a></li>
    30. <li><a href="#">极尽升华</a></li>
    31. <li class="dropdown">
    32. <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
    33. aria-expanded="false">极道帝兵<span class="caret"></span></a>
    34. <ul class="dropdown-menu">
    35. <li><a href="#">荒塔</a></li>
    36. <li><a href="#">仙钟</a></li>
    37. <li><a href="#">吞天魔罐</a></li>
    38. <li role="separator" class="divider"></li>
    39. <li><a href="#">青莲帝兵</a></li>
    40. <li role="separator" class="divider"></li>
    41. <li><a href="#">仙铁棍</a></li>
    42. </ul>
    43. </li>
    44. </ul>
    45. <form class="navbar-form navbar-left">
    46. <div class="form-group">
    47. <input type="text" class="form-control" placeholder="Search">
    48. </div>
    49. <button type="submit" class="btn btn-default">Submit</button>
    50. </form>
    51. <ul class="nav navbar-nav navbar-right">
    52. <li><a href="#">Link</a></li>
    53. <li class="dropdown">
    54. <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
    55. aria-expanded="false">Dropdown <span class="caret"></span></a>
    56. <ul class="dropdown-menu">
    57. <li><a href="#">Action</a></li>
    58. <li><a href="#">Another action</a></li>
    59. <li><a href="#">Something else here</a></li>
    60. <li role="separator" class="divider"></li>
    61. <li><a href="#">Separated link</a></li>
    62. </ul>
    63. </li>
    64. </ul>
    65. </div><!-- /.navbar-collapse -->
    66. </div><!-- /.container-fluid -->
    67. </nav>
    68. <div class="container-fluid">
    69. <div class="row">
    70. <div class="col-md-3">
    71. <div class="list-group">
    72. {% block ft %}
    73. <div class="list-group">
    74. <a href="/home/" class="list-group-item active">
    75. 欢迎来到仙侠世界
    76. </a>
    77. <a href="/login/" class="list-group-item">登陆星空古路</a>
    78. <a href="/register/" class="list-group-item">加入圣地考核</a>
    79. <a href="#" class="list-group-item">修仙技术支持</a>
    80. <a href="#" class="list-group-item">更多</a>
    81. </div>
    82. {% endblock %}
    83. </div>
    84. </div>
    85. <div class="col-md-9">
    86. <div class="panel panel-info">
    87. <div class="panel-heading">九秘</div>
    88. {% block content %}
    89. <div class="panel-body">
    90. <div class="jumbotron">
    91. <h1>少年,你想变强吗</h1>
    92. <p>加入我们</p>
    93. <p><a class="btn btn-primary btn-lg" href="#" role="button">快来,快来</a></p>
    94. </div>
    95. <div class="row">
    96. <div class="col-sm-6 col-md-4">
    97. <div class="thumbnail">
    98. <img src="https://img1.baidu.com/it/u=803199455,778449086&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=1080"
    99. alt="...">
    100. <div class="caption">
    101. <h3>Thumbnail label</h3>
    102. <p>...</p>
    103. <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"
    104. class="btn btn-default"
    105. role="button">Button</a>
    106. </p>
    107. </div>
    108. </div>
    109. </div>
    110. <div class="col-sm-6 col-md-4">
    111. <div class="thumbnail">
    112. <img src="https://img1.baidu.com/it/u=3707885883,1615845000&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=337"
    113. alt="...">
    114. <div class="caption">
    115. <h3>Thumbnail label</h3>
    116. <p>...</p>
    117. <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"
    118. class="btn btn-default"
    119. role="button">Button</a>
    120. </p>
    121. </div>
    122. </div>
    123. </div>
    124. <div class="col-sm-6 col-md-4">
    125. <div class="thumbnail">
    126. <img src="https://img1.baidu.com/it/u=1395000385,3610786620&fm=253&fmt=auto&app=120&f=JPEG?w=889&h=500"
    127. alt="...">
    128. <div class="caption">
    129. <h3>Thumbnail label</h3>
    130. <p>...</p>
    131. <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"
    132. class="btn btn-default"
    133. role="button">Button</a>
    134. </p>
    135. </div>
    136. </div>
    137. </div>
    138. </div>
    139. </div>
    140. {% endblock %}
    141. </div>
    142. </div>
    143. </div>
    144. </div>
    145. {% block js %}
    146. {% endblock %}
    147. </body>
    148. </html>

     login.html模块

    1. {% extends 'home.html' %}
    2. {% block css %}
    3. <style>
    4. h1{
    5. color:red;
    6. }
    7. </style>
    8. {% endblock %}
    9. {% block ft %}
    10. <div class="list-group">
    11. <a href="/home/" class="list-group-item active">
    12. 欢迎来到仙侠世界
    13. </a>
    14. <a href="/login/" class="list-group-item">登陆星空古路</a>
    15. <a href="/register/" class="list-group-item">加入圣地考核</a>
    16. </div>
    17. {% endblock %}
    18. {% block content %}
    19. <h1 class="text-center">登陆页面</h1>
    20. <div class="row">
    21. <div class="col-md-8 col-md-offset-2">
    22. <form action="">
    23. <div class="form-group">
    24. 用户名:<input type="text" class="form-control">
    25. </div>
    26. <div class="form-group">
    27. 密码:<input type="text" class="form-control">
    28. </div>
    29. <div class="form-group">
    30. <input type="submit" class="btn btn-success btn-block" value="提交">
    31. </div>
    32. </form>
    33. {% include 'hahah.html' %}
    34. </div>
    35. </div>
    36. {% endblock %}
    37. {% block js %}
    38. <script>
    39. alert('login')
    40. </script>
    41. {% endblock %}

    register.html 模块

    1. {% extends 'home.html' %}
    2. {% block ft %}
    3. <div class="list-group">
    4. <a href="/home/" class="list-group-item active">
    5. 欢迎来到仙侠世界
    6. </a>
    7. <a href="/login/" class="list-group-item">登陆星空古路</a>
    8. <a href="/register/" class="list-group-item">加入圣地考核</a>
    9. </div>
    10. {% endblock %}
    11. {% block content %}
    12. <h1 class="text-center">注册页面</h1>
    13. <div class="row">
    14. <div class="col-md-8 col-md-offset-2">
    15. <form action="">
    16. <div class="form-group">
    17. 用户名:<input type="text" class="form-control">
    18. </div>
    19. <div class="form-group">
    20. 密码:<input type="text" class="form-control">
    21. </div>
    22. <div class="form-group">
    23. <input type="submit" class="btn btn-success btn-block" value="提交">
    24. </div>
    25. </form>
    26. </div>
    27. </div>
    28. {% endblock %}
    29. {% block js %}
    30. <script>
    31. alert('register')
    32. </script>
    33. {% endblock %}

    END

  • 相关阅读:
    aop面向切面运用
    policy gradient详解(附代码)
    【前端】彻底搞懂HTTP协议
    Java从控制台接收用户输入的一行英文句子,把句子的最前面两个单词移到句子的最后面去,并整理句子的大小写及标点符号,将新的句子输出
    软件测试行业35岁职场魔咒,你准备怎么应对?
    Ubuntu服务器配置qq邮箱发送信息
    一文搞懂APT攻击
    C语言程序设计(三)高级特性
    【MyBatis-Plus】快速精通Mybatis-plus框架—快速入门
    bignumber.js
  • 原文地址:https://blog.csdn.net/qq_38104453/article/details/134450525