Django's template system BASIC

Django's template system BASIC

A grammar

Template rendering of official documents

About templates to render you only need to remember two special symbols (syntax):

  • {{ }}with{% %}
  • Variable associated with {{}}, {logic associated with %%}.

Bivariate

Click Django template language syntax used in: {{name}} variable.

  When the template engine encounters a variable, it will calculate the variable, and then replace it with the result itself. Named variables include any alphanumeric and underscore ( "_") combination. Variable names can not contain spaces or punctuation.

  Depth inquiry stronghold symbol (.) Has a special meaning in the template language. When the template system encounters a dot ( "."), It will be in this order inquiries:

    Dictionary lookup (Dictionary lookup)
    property or method query (Attribute or method lookup)
    digital index query (Numeric index lookup)

  Precautions:

  1. If the value of calculation result is called, it will be invoked with no parameters. Result of the call will be the value of the template.
  2. If variables does not exist, the system will insert the value string_if_invalid template option, which is the default setting is '' (the empty string).

  A few examples:

  view code:

from django.shortcuts import render


# Create your views here.
def index(request):
   num = 100
   name = 'anwen'
   lst = ['安文', 'didi']
   # lst=[]

   dic = {'name': '安文', 'age': 23, 'hobby': '游泳'}

   class Animal():
      def __init__(self):
         self.kind = 'dog'

      def eat(self):
         return 'chi'

   a = Animal()
   # xx='ll'

   filesize = '432511234.234'

   words = 'hello word i have a dream'

   tag = '<a href="http://www.baidu.com">百度</a>'
   import datetime
   time = datetime.datetime.now()

   # return render(request,'index.html',{'num':num,'name':name,'lst':lst,'dic':dic})
   print(locals())
   return render(request, 'index.html', locals())

Template index supported in writing:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>数字:{{ num }}</p>
<p>字符串:{{ name }}</p>
<p>列表:{{ lst }}</p>
<p>{{ lst.2 }}</p>
<p>字典:{{ dic }}</p>
<p>{{ dic.name }}</p>
<p>类方法:{{ a.eat }}</p>
</body>
</html>

Three filters

In Django template language by using filters to change the display of variables.

  The syntax of the filter: {{value | filter_name: Parameter}}

  Use pipe symbol "|" applying a filter.

  For example: {{name | lower}} then the variable name will show its value after the application of lower filter. lower in action here is all lowercase text.

  Precautions:

  1. Filter supports the "chain" operation. I.e., a filter output as input to another filter.
  2. Filters can accept parameters, for example: {{sss | truncatewords: 30}}, which will display the first 30 words of sss.
  3. Filter parameter contains a space, it must be wrapped in quotes. Such as comma and a space used to connect the elements of a list, such as: {{list | join: ','}}
  4. '|' Around is no space without a space with no spaces

  Django template language provides about sixty built-in filter.

default

    If a variable is false or empty, the default values ​​given. Otherwise, use the value of the variable.

<p>{{ xx|default:'啥都没有' }}</p>  #如果value没有传值或者值为空的话就显示啥都没有

length

    Returns the length, acting on the string and the value list.

    {{ value|length }}

    Returns the value of the length, such as the value = [ 'a', 'b', 'c', 'd'], then, 4 is displayed.

{#获取数据长度#}
<p>{{ lst|length }}</p>

filesizeformat

    Value formatted as a "human readable" file size (e.g. '13 KB', '4.1 MB', '102 bytes', etc.). E.g:

filesize = '432511234.234'
<p>{{ filesize|filesizeformat }}</p>    #如果filesize是432511234.234,输出将会是412.5 MB

slice

    Slice, if the value = "hello world", as well as other types of data slice

{#切片,如果 value="hello world",还有其他可切片的数据类型#}
<p>{{ words|slice:'6:10' }}</p>

date

    Formatting, if value = datetime.datetime.now ()

{{ value|date:"Y-m-d H:i:s"}}
关于时间日期的可用的参数(除了Y,m,d等等)还有很多,有兴趣的可以去查查看看。

truncatechars

    If the string of characters is more than a specified number of characters, it will be truncated. Translatable strings will be truncated sequence at the end of the ellipsis ( "...").

    Parameters: the number of characters truncated

words = 'hello word i have a dream'
{{ words|truncatechars:9}} #注意:最后那三个省略号也是9个字符里面的,也就是这个9截断出来的是6个字符+3个省略号,有人会说,怎么展开啊,配合前端的点击事件就行啦

truncatewords

    Truncates the string after a certain number of words, how many words are cut.

    例如:‘hello word i have a dream’,

{{ value|truncatewords:3}}  #上面例子得到的结果是 'hello word i...'

cut

    Removing all variable value given the same string

hello word i have a dream
{{ value|cut:' ' }}     #hellowordihaveadream

join

    String connection list, {{list | join: ','}}, as a Python str.join (list)

lst = ['安文', 'didi','yage']
<p>{{ lst|join:'+' }}</p>   #安文+didi+yage

Four labels Tags

Tag looks like this: {% tag %}. Tag is more complex than a variable: some additional information creating in the output text, a number or to control flow through the logic loop, some variables will be used to load subsequent to the template. Some tags require the start and end tags (e.g., {% tag %} ...tag content ... {% endtag%}).

for labels

    Through each element: write for, and then automatically generate the tab key structure for the cycle, the cycle is very basic, so simple use, there is no break and the like, complex functions, you have to pass js

{% for l in lst %}
    <p>{{ forloop.counter }}{{ l }}</p> <!--凡是变量都要用两个大括号括起来-->
<!--for ... empty-->
<!--for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。-->
{% empty %}
    <p>no</p>
{% endfor %}

{#遍历一个字典#}
{% for key,value in dic.items %}
    <p>{{ key }}--{{ value }}</p>
{% endfor %}

NOTE: cycle number can be displayed {{forloop}}, must be used inside the loop  

forloop.counter            当前循环的索引值(从1开始),forloop是循环器,通过点来使用功能
forloop.counter0           当前循环的索引值(从0开始)
forloop.revcounter         当前循环的倒序索引值(从1开始)
forloop.revcounter0        当前循环的倒序索引值(从0开始)
forloop.first              当前循环是不是第一次循环(布尔值)
forloop.last               当前循环是不是最后一次循环(布尔值)
forloop.parentloop         本层循环的外层循环的对象,再通过上面的几个属性来显示外层循环的计数等

if the label

    {% if %}Have a variable evaluation, if its value is "True" (exists, is not empty, and not false boolean value type), the block will output the corresponding content. if statement supports and, or, ==,>, <,! =, <=,> =, in, not in, is, is not to judge, pay attention to the conditions on both sides spaces.

{% if num > 100 %}
    <p>大于100</p>
{% elif num < 100 %}
    <p>小于100</p>
{% else %}
    <p>等于100</p>
{% endif %}
{#Django的模板语言不支持连续判断,即不支持以下写法:#}
{#{% if a > b > c %}#}
{#...#}
{#{% endif %}#}

with

    Use a simple name cache a complex variable, used to a complex variable aliases, when you need to use an "expensive" method (such as database access) many times when it is very useful

    E.g:

    Note that no space around the equal sign.

{% with dic.hobby as hb %}
    <p>{{ hb }}</p>
{% endwith %}

{#注意:等号左右不要加空格。#}
{% with hb=dic.hobby  %}
    <p>{{ hb }}</p>
{% endwith %}

csrf_token

    When we submit the form to post way, will complain, remember that we are inside the middleware configuration settings inside the csrf a defense mechanism to write-off the ah, itself should not be written off, but should learn how to use it, and do not to make their operation is forbiden, be able to get through this thing.

    This tag is used CSRF protection,

    In the form of which form page (note that the form in which form) on any position to write {% csrf_token%}, this thing when rendering templates replaced with the hidden value of this tag is a random string, when submitted, this thing has also been submitted, the first thing is the back-end rendering when we add to the page, then when you submit data via a form I'll give you a form, you take the content I've known you, without , I will forbid you, because the background we django also exist with this thing, and a same value you this value, you can do the corresponding verification is not I give you a token, to store the value of the things we later learn, you first I know on the line, just like the one we give the user a backstage pass, if you follow my users do not have to post this to your normal page submission form data, or that you did not ask me to go to this landing page, but direct simulation request to submit the data, then I can tell you that the request is illegal, anti-reptile or a malicious attack on my website, Middleware later when we go into detail in this thing, but now you have to understand how it happened, understand why django will add this set of defense.

    Sending a post request crawler simple simulation:

import requests

res = requests.post('http://127.0.0.1:8000/login/',data={
    'username':'chao',
    'password':'123'
})

print(res.text)

csrf_token defense mechanism to bypass csrf

#views.py
from django.shortcuts import render
def token(request):
   return render(request, 'token.html')
<!--token.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>token</title>
</head>
<body>
<form action="" method="post">
    {% csrf_token %}

    用户名: <input type="text" name="username">
    <button>提交</button>
</form>
</body>
</html>

Five template inheritance

Django template engine is the most powerful and most complex part of the template is inherited. Template inheritance allows you to create a basic "skeleton" template that contains all the elements of your site, and you can define templates quilt blocks can covered.

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 模板
    url(r'^base/', views.base),
    url(r'^menu1/', views.menu1),
    url(r'^menu2/', views.menu2),
    url(r'^menu3/', views.menu3),
]
#views.py
from django.shortcuts import render
def base(request):  #模板函数
   return render(request, 'base.html')  #模板页面
def menu1(request):
   return render(request, 'menu1.html')
def menu2(request):
   return render(request, 'menu2.html')
def menu3(request):
   return render(request, 'menu3.html')
<!--menu1.html-->
{% extends 'base.html' %}
{% block content %}
    menu1
{% endblock %}

<!--menu2.html-->
{% extends 'base.html' %}
{% block content %}
    menu2   
{% endblock %}

<!--menu3.html-->
{% extends 'base.html' %}
{% block content %}
    menu3   
{% endblock %}

6-pack

The page content may be used, such as navigation, footer information components stored in a separate file and then use where needed, can be introduced anywhere in the file by the following syntax.

{% include 'navbar.html' %}
#urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 组件nav
    url(r'^nav/', views.nav),
    url(r'^newnav/', views.nav),
]
#views.py
from django.shortcuts import render
def nav(request):
   return render(request,'nav.html')
def newnav(request):
   return render(request,'newnav.html')

There follows the navigation bar, nav.html

<!--nav.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nav</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .nav {
            background: red;
            height: 40px;
        }
    </style>
</head>
<body>

<div class="nav">
    <a href="">导航</a>
    <a href="">导航</a>
    <a href="">导航</a>
    <a href="">导航</a>
    <input type="text">
    <button>搜索</button>
</div>
</body>
</html>

With the newnav.html components

<!--newnav.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{# 组件#}
{#可以将常用的页面内容如导航条,页尾信息等组件保存在单独的文件中,然后在需要使用的地方,文件的任意位置按如下语法导入即可。#}
{% include 'nav.html' %}
</body>
</html>

The difference between simple components and plug-ins

组件是提供某一完整功能的模块,如:编辑器组件,QQ空间提供的关注组件 等。
而插件更倾向封闭某一功能方法的函数。
这两者的区别在 Javascript 里区别很小,组件这个名词用得不多,一般统称插件。

Guess you like

Origin www.cnblogs.com/an-wen/p/11204193.html