template template language

Template Rendering

Render to html page views by the view function

标签{{ 变量 }}/标签   {% 逻辑 %} -- 标签

Universal point

<h1>91李业网</h1>
<h2>{{ name }}</h2>
<h2>{{ d1.items }}</h2>
<h2>我是"{ {{ l1.1 }} }"</h2>#三个括号必须加空格
<h2>{{ num }}</h2>
<h2>{{ obj.p }}</h2>  #如果调用的方法需要显性传参,可以印象传产,sorry用不了
注意点
可以嵌套点
可以自动执行函数
locals()函数会以字典类型返回当前位置的全部局部变量
return render(request,'home.html',locals())
字典类型的数据传入home.html
 return render(request,'home.html',{'name':name,})#指定传入html
可以直接拿来引用

filter

Filter template rendered on the basis of

Note that the value must pass: the specified value

default**

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

{{ value(变量)|default:"nothing"}}

If value is null or the value is not passed, then nothing is displayed

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.

filesizeformat

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

{{ value(变量)|filesizeformat }}

If the value is 123456789, the output will be 117.7 MB.

slice

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

{{value(变量)|slice:"2:-1"}}

date

    Formatting, if value = datetime.datetime.now (

{{ value(变量)|date:"Y-m-d H:i:s"}}

  Parameters available on the date and time (except Y, m, d, etc.) there are many, are interested can look to look.

Safe (identified as tag)

    Django template during the template when rendering HTML tags will be syntactic and JS tags automatically escaped, for obvious reasons, this is for security, django worried that this data is added by the user, for example, if someone gives you time to write reviews some js code, the review a submission, js code will execute you, so that you are not able to carry out some of the bad child, write a pop cycle of death, and that the browser can use it, is not it will always pop ah this is called xss attack, so the browser will not let you do so, you escaped. But sometimes we might not want these HTML elements are escaped, for example, we do a content management system, add background of the article is modified, these modifications may be raised by a similar FCKeditor editing the HTML modifier text, escaped, then automatically displayed if the source file is to protect HTML tags. To turn off the automatic Django escaped HTML in two ways, if it is a single variable we can filter | tell Django "safe" way to secure this code is not necessary to escape.

    We went to the local network to see, to see the results after the browser is rendering, you can see through that part of the response of the network. This is a special symbol tag all wrapped up, not a label, it is django do a thing.

    img

such as:

value = " point I " and value = ""

{{ value(变量标签)|safe}}

    Many sites, will be on content submitted by you to filter some sensitive words, special characters, labels, pornography, gambling vocabulary and so on, as you submit content, other people will detect the contents of your submission, if you include these terms, do not let you submit, in fact, this is the fundamental way to solve xss attacks, such as blog garden:

    img

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

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

truncatewords

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

Rei如: 'hello girl hi baby yue ma',

{{ value|truncatewords:3}}  
#上面例子得到的结果是 'hello girl h1...' 以空格为分界点

cut

Removing all variable value given the same string

{{ value|cut:' ' }}

If value is 'i love you', then the output 'iloveyou'.

join

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

<h1>{{ name|join:"+"}}</h1>

timesince (understand)

The date format to time since that date (e.g., "4 days, 6 hours") self.

Optional use of a variable parameter, which is used as a point of comparison date included (without parameters, as a comparison point is now). For example, if the date is an example of blog_date June 2006 midnight on the 1st, the date and comment_date instance, 2006 at 8:00 on June 1, the following will return "8 hours":

{{ blog_date|timesince:comment_date }}

Min is the smallest unit used for any date in the future with respect to the comparison point, it will return "0 minutes."

timeuntil (understand)

Similar to timesince, except that it measures the time from now on until a given date or date and time. For example, if today is June 1, 2006, and conference_date instance is reserved date June 29, 2006, the {{conference_date | timeuntil}} will return to "four weeks."

Use of optional parameters, which is used as a comparison point comprising date (rather than the current) variable. If from_date contains 2006 June 22, the following will return "a week":

{{ conference_date|timeuntil:from_date }}

label

The for loop label

#循环列表等
{% for person in person_list %}
    <p>{{ person.name }}</p>  <!--凡是变量都要用两个大括号括起来-->
{% endfor %}
#循环字典
{% for key,val in dic.items %}
    <p>{{ key }}:{{ val }}</p>
{% endfor %}
#循环字符串
{% for i in name %}
    <h2>{{ i }}</h2>
{% endfor %}
#empty
{% for person in person_list %}
    <p>{{ person.name }}</p>  <!--凡是变量都要用两个大括号括起来-->
{% empty %}
    <p>没有找到东西!</p>
{% endfor %}


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

            <li>{{ forloop.counter }}-- {{ forloop.parentloop.counter }} === {{ k }} -- {{ v }}</li>

        {% endfor %}

    {% endfor %}

determining if tags

{% if num > 100 or num < 0 %}
    <p>无效</p>  <!--不满足条件,不会生成这个标签-->
{% elif num > 80 and num < 100 %}
    <p>优秀</p>
{% else %}  <!--也是在if标签结构里面的-->
    <p>凑活吧</p>
{% endif %}

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断,注意条件两边都有空格。

with (from Alias)

方法1
{% with total=business.employees.count %}  #注意等号两边不能有空格
    {{ total }} <!--只能在with语句体内用-->
{% endwith %}
方法2
{% with business.employees.count as total %}
    {{ total }}
{% endwith %}

render

locals returns the current page to show all the variables to a dictionary

Template syntax

Template inheritance

The purpose is to: reduce redundant code

Commonly used in the left menu bar

The parent class directly take over the corresponding label use

{% block content(变量可以随便命名)%}

{{block.super}}#延续父类的变量

包裹什么就修改什么 

{% endblock %}

可以修改
继承页面{% extends 'base.html' %}
1.创建一个xx.html页面作为模板,其他页面来继承他
2。在母版中定义block块
{% block content %}<!--预留钩子。供其他html页面使用,自定义自己内容>
3 其他子页面继承写法
{% extends 'base.html' %}必须放在页面开头 #相当于继承子页面的声明
4 页面中写和母版中名字相同的block块,从而来显示自定义的内容
    {% block content %}  <!-- 预留的钩子,共其他需要继承它的html,自定义自己的内容 -->
        {{ block.super }}  #这是显示继承的母版中的content这个快中的内容
        这是xx1
    {% endblock %}

Package

Plug-in components smaller than

1 创建html页面,里面写上自己封装的组件内容,xx.html
2 新的html页面使用这个组件
    {% include 'xx.html' %}

Used corresponds to the external component is introduced directly used but is not directly modified

{% include 'xx.html' %}

Custom tags and filters

Note that the value must pass one correspondence

Custom tags and filters must create a folder in the folder below py file written inside def function

1 在应用下django文件夹下创建一个叫做templatetags的文件夹(名称不能改),在里面创建一个py文件,例如xx.py

2 在xx.py文件中引用django提供的template类,写法
    from django import template
    register = template.Library() #register变量名称不能改    

Defining filters

1 在应用下django文件夹下创建一个叫做templatetags的文件夹(名称不能改),在里面创建一个py文件,例如xx.py

2 在xx.py文件中引用django提供的template类,写法
    from django import template
    register = template.Library() #register变量名称不能改 
[email protected]#自定义过滤器的声明,装上这个装饰器解释过滤器了   参数至多两个
def xx(v1,v2):
 #{{name(外部传参第一个值)|xx(过滤器名称):第二个值}}
    return v1+"xx"#自定义过滤 返回值
#结果 v1xx
使用:
    {% load xx %}#开头引用
    内容
    {{ name|xx:'oo' }}

Custom label

过程:
name是一个值 5是第二个值
#def huxtag(n1(第一个值),n2(第二个值))
前端:{% huxtag name 5 %} 
# 自定义标签 没有参数个数限制
后端:@register.simple_tag
def huxtag(n1,n2):  #冯强xx  '牛欢喜'
    '''
        :param n1:  变量的值 name前面的
        :param n2:  对应5传的参数 如果不需要传参,就不要添加这个参数
        :return:
        '''
    return n1+n2

From one custom label

执行过程:
1.通过urls的函数返回li.html
2.执行到{% res name %}开始执行res自定义标签
3.把name值传给result.html
4.最后把渲染过标签返回给li.html(通过res函数处理过的数据)
#li.html写法
'''
{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% res name %}
</body>
</html>
'''
#result.html页面代码
'''
<body>
{% for i in li %}
    <div>{{ i }}</div>
{% endfor %}
</body>
'''
# inclusion_tag 返回html片段的标签
@register.inclusion_tag('result.html')
def res(n1): #n1 : ['aa','bb','cc']

    return {'li':n1 }
使用:
    html页面
    {% res a %}

Template rendering end of the replacement string

url aliases and reverse analysis (alias)

别名写法
url(r'^index2/', views.index,name='index'),
#name=别名
反向解析
通过reverse 解析出路径
后端(py文件): 
    from django.urls import reverse
reverse('别名') 
例如:reverse('index') -- /index2/
html: 
    {% url '别名' %} -- 
例如:{% url 'index' %} -- /index2/

Reverse analysis with parameters

后端:
from django.urls import reverse
reverse('index',args=(10))--/index2/10
html:
带参数的反向解析
{% url '别名' 参数1 参数二 %}
例如
{% url 'index' 10 %}--/index2/10
<a href='/index2/10'>hhh</a>

示例
html页面a标签写法
<a href="{% url 'app01:index' 10 %}">hhh</a>

app01下面视图函数(views.py)写法
from django.shortcuts import render,HttpResponse,redirect
from django.urls import reverse

def ppt(request):
    return redirect(reverse('app01:index',args=(10)))
app01下面路径(urls.py)写法
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
  url(r'^index/(\d+)/',views.index,name="index",
    url(r'^home/',views.home,name="home"),
      ]

url namespace

Route distribution include

Route distribution path is to give a lot of pages in each corresponding app, to facilitate unified management

#注意include是模块里面的方法要引用才能发挥作用
1 在每个app下创建urls.py文件,写上自己app的路径
2 在项目目录下的urls.py文件中做一下路径分发,看下面内容
 在主文件夹里面的urls分发   
    from django.conf.urls import url,include
    from django.contrib import admin

    urlpatterns = [
        # url(r'^admin/', admin.site.urls),
        #app01/home/直接跳转到对应app01下面的urls
     url(r'^app01/',include('app01.urls')),
url(r'^app02/', include('app02.urls')),
    ]

Namespace namespace

A regular in order to avoid conflicts resulting in the url alias

使用格式:
后端(py文件):reverse('命名空间名称:别名') 
        -- reverse('app01:home') 
hmtl:{% url '命名空间名称:别名' %}  
        -- {% url 'app01:home' %}

from django.conf.urls import url,include
from django.contrib import admin
django下面的文件夹urls.py写法
urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^app01/', include('app01.urls',namespace='app01')),#app01/home/
    url(r'^app02/', include('app02.urls',namespace='app02')),
    
]
app01下面的urls.py 写法
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^home2/', views.home,name="home"),
    url(r'^index/', views.index,name="index"),
    url(r'^ppt/', views.ppt,name="ppt1"),
]
'''
app01下views.py写法
'''
from django.shortcuts import render,HttpResponse,redirect
from django.urls import reverse
#render的三个参数 是在html 之前就渲染好了 例如 {"name":name}
# 模板X HttpResponse("字符串") 返回一个字符串页面
# Create your views here.

def home(request):
    return render(request,"home2.html")
def index(request):
    return render(request,"index.html")
def ppt(request):
    return redirect(reverse("app01:index"))

Guess you like

Origin www.cnblogs.com/strawberry-1/p/11666393.html