django 模板 (ああああああああ!かぴ)

一 常用
1. {{ 不存在 | default : "xx" }}
2. {{ name | length }}
3. {{ xx | slice "1:-1" }}
4. {{ now | date: "Y-m-d H:i:s" }} now = datetime.now()
5. {{ xx | truncatechars : x }}      截取文字
6. {{ xx | truncatewords : x }}      截取单词
7. {% for k,v in d.item %}
           {{ k }} {{ v }}
     {% endfor %}
8. {% for person in person_list %}
     {{ person.name }}
 { % empty %}
   {{ xxx }}
   {% endfor %}
9. 

{% for name in name_list %}<li class="{% if forloop.first %} 'sb' {% endif %}">
{{ forloop.revcounter }} - {{ name }}</li>
{% endfor %}

forloop.counter 当前索引值默认从1开始
forloop.counter 0 从1开始
forloop.revcounter 倒序索引值默认以1结束
forloop.revcounter 0      以0结束
forloop.firs          是不是第一次循环
forloop.last

二 自定义

在app下建templatetags python package,再新建个py文件

mytags.py

 

from django import template
register = template.Library()   # 注册


# 自定义filter
@register.filter(name="aki")
def multi(x, y):
    return x*y
# 模板用法是 {{ num | aki:2}}   num已经被指定为12, x是管道符前面的参数,y是后面的参数如 2  最多两个参数
# 注意上面的aki:2 :2 不能有空格,否则报参数个数的错误


# 自定义simple_tag
@register.simple_tag(name="desky")
def my_input(x, y, z):
    return x*y*z
# 模板用法是 {% desky "x" "xo" "xoo"%}    可以定义多个参数


# 自定义inclusion_tag
@register.inclusion_tag('test.html')
def show_result(n):
    n = 1 if n < 1 else int(n)
    data = ["第{}项".format(i) for i in range(1, n+1)]
    return {"data": data}

text.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
{% load mytags %}
{% show_result 5 %}
{% desky 2 5 6%}
{{ num | aki:23 }}
{##}
</body> </html>

test.html

<ul>
    {% for choice in data %}
        <li>{{ choice }}</li>
    {% endfor %}
</ul>
几点说明
filter: 最多两个两个参数,可以进行逻辑判断,{% if i|multi > 1000 %} .....,还有千万注意{ num | aki:2}}不能有空格 引用是 {{}}

simple_tag : 可以传多个参数,但不能进行逻辑判断,% desky "x" "xo" "xoo"%} 引用时 {%%}
inclusion_tag('xx.html'): 是将一段html 插入到哪里,这里是将test插入到text中,{% show_result 5 %} 要引用,还要将参数传递进去

最后说的是,新建的python package 必须叫templatetags, 别忘引入{% load mytags %}









posted @ 2019-03-15 15:39  DeskyAki  阅读(113)  评论(0编辑  收藏  举报