django(2) 模板

tags

for 循环
格式:

<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% endfor %}
</ul>

for 循环可用的参数;

  forloop.counter      从当前的索引值  从1

  forloop.counter0    从当前的索引值  从0

  forloop.revcounter 当前的倒序索引值 从1

  forloop.revcounter0     当前的倒序索引值  从0
  forloop.first      当前循环是不是第一次循环(布尔值) 

  forloop.last      当前循环的是不是最后一次(布尔值)

  forloop.parentloop    本层循环的外层循环

可以嵌套很多层

for ...... empty

<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% empty %}
    <li>空空如也</li>
{% endfor %}
</ul>

  

if ,elif ,else

if 判断5>2>1 时和python的不一样   它是先对比前边得到值后对比后边

{% if user_list %}
  用户人数:{{ user_list|length }}
{% elif black_list %}
  黑名单数:{{ black_list|length }}
{% else %}
  没有用户
{% endif %}

判断商的时候用 divisibleby:数字

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。

with 起名

#{% with p_list.0.name as  chenrun %}#}
{##}
{#    {{ chenrun }}#}
{#    {{ chenrun }}#}
{#    {{ chenrun }}#}
#{% endwith %}#}

csrf_token

不用在setting引掉的csrf

注意事项:

  1不能连续判断

  2,django 的模板语言中的属性的优先级大于方法  

. tags
 2. 母版和继承
  1. 母版
   就是一个普通的HTML文件,提取多个页面的公共部分
   减少代码量  修改十分方便
   
   定义block块
   
  2. 使用(继承)
   在子页面中
    {% entends 'base.html' %}
    重新修改block块中的内容
  3. 注意事项:
   1. 把{% extends 'base.html' %} 写在第一行
   2. 修改的内容写在block中,写在外面不显示
   3. {% extends name %}   name应该是变量 或者是字符串  继承母版的名字
   4. 母版中定义多个block块,一般还有 js 块 和 css块
    
  
 
 3. 组件
  1. 就是一小段HTML代码   多个页面都用到的内容 nav.html
  2. 在任意的模板中使用
   {% include 'nav.html' %}
  
   
  
 4. 静态文件相关
 
  1. {% load staticfiles %} 或者 {% load static %}
  2. {% static 'css/pub.css' %}  ——》 先去settings中获取STATIC_URL的配置,和后面提供的参数进行拼接
  
  1. {% load static %}
  2.
   <link rel="stylesheet" href="{% get_static_prefix %}css/pub.css">
  
  
  
 5. 自定义simpletag和自定义inclusion_tag
  1. 在app下创建一个名叫templatetags的python包
  2. 在templatetags里建一个py文件
  3. 在py文件中编辑:
   from django import template
   register = template.Library()
   
   
   @register.simple_tag
   def join_str(arg1, arg2, arg3,*args,**kwargs):
    print(args)
    print(kwargs)
    return '_'.join([arg1, arg2, arg3])+'*'.join(args)
    
   @register.inclusion_tag('pagination.html')
   def pagination(total, current):
    return {'total': range(1, total + 1), 'current': current}

4,

使用:

{%load mytags%}

{{变量|dsb:'参数'}} filter

{%add_b ''%}simple_tag

{%show_li 5%}inclusion_tag 

注意特殊的inclusion_tag

执行的顺序需要注意先从html中获取参数,进入到函数中,进行调用另一个封装好的html,并且把参数传递给后者的html.

原文地址:https://www.cnblogs.com/lnrick/p/9627989.html