django 模板语法

 1 django 模板语法
 2 {{ }} <!--变量相关-->
 3 {% %} <!--逻辑相关-->
 4 {# 对象的属性优先级高于内置方法 #}
 5 {# 在django中不支持逻辑判定式子连写:a>b>c 要写为 a>b and b>c #}
 6 {# JS中:t=a>b return t>c #}
 7 {# python中为a>b and b>c #}
 8 forloop.first
 9 forloop.last
10 forloop.counter
11 forloop.revcounter
12 forloop.parentloop.*
13 eg:
14 forloop.parentloop.counter
15 
16 {% for use in user_list %}
17     <li>{{ use.name }}</li}
18 {% empty %}
19     <li>{{ 空的 }}</li}
20 {% endfor %}
21 <!--定义中间变量-->
22 {# django中的注释 #}
23 {% with total=name_list.2.1 %}
24     {{ total }}
25 {% endwith %}
26 
27 1.常用的内置filter
28     1.length
29     2.filesizeformat
30     3.slice
31     4.truncatechars
32     5.safe ----> XSS攻击跨站脚本攻击
33     6.default
34     7.data:'Y-m-d H-i-s'
35 2.自定义filter
36     1.新建python package 包名为:templatetags在app中
37     2.在包中写自己的filter python file
38     3.事例:
39         from django import template
40         register = template.Library()
41 
42         @register.filter(name="sb")
43         def add_sb(arg):
44             return "{}__dsb".format(arg)
45 
46         @register.filter(name="dsb")
47         def add_sb(arg,arg2):
48             return "{}___{}".format(arg,arg2)
49     4.在使用自定义filter的文件中 {% load py文件名字 %}
 1 Django
 2 
 3 # 新建app 要去django settings.py 去注册
 4 # orm 无法创建数据库
 5 # mysqldb pysql 连接数据库
 6 # 使用pymsql 代替mysqldb
 7 # orm对应的类写在app中的models中3
 8 # 类必须继承自 models.Model
 9 # 执行 python manage.py makemigrations
10 #    python manage.py migrate
食用须知:
    {# 继承母版 #}
    {% extends 'base.html' %}  ---> 这句话必须放在子页面第一行
    base.html  要加引号
    可以在base.html中定义很多块 {% block name %}{% endblock %}
    views.py 返回的是对应的子页面 而不是base.html
    
静态文件路径灵活写法:
<!--自动拼接-->
{% load static %}
src= "{% static 'file_path' %}"
<!--手动拼接-->
src= "{% get_static_prefix%}file_path"

<!--将静态文件路径保存至变量中 以变量方式引用-->
{% load static %}
<img src="(% static '111.jpg' as xiao %}">
<img src="{{ xiao }}">


<!--simpletag-->
与自定义定义filter一致
1.在app中添加python package 
2.在包下写.py文件
eg:mysimpletag.py
from django import template
register = template.Library()

@register.simple_tag(name= "yimi")
def my_merge(arg,arg1,arg2):
    return "{}{}{}".format(arg,arg1,arg2)
    
3.{% load mysimpletag %}
{% yimi "aaa" "bbb" "ccc" %}

<!--inclusiontag-->

与自定义定义filter一致
1.在app中添加python package 
2.在包下写.py文件
eg:myinclusiontag.py
from django import template
register = template.Library()

@register.inclusion_tag("result.html")
def show_results(n):
    n=1 if n<1 else int(n)
    data = ["第()项".format(i) for i in range(1,n+1)]
    return {"result":data}

result.html
<ul>
    {% for choice in result %}
    <li>{{ choice }}</li>
    {% endfor %}
</ul>
    
3.{% load mysimpletag %}
{% show_results 100 %}

 

posted @ 2019-04-06 20:17  Priceless  阅读(31)  评论(0)    收藏  举报