python Tags 母板 组件 静态文件相关 自定义simpletag inclusion_tag

一.Tags
(一)for
1.基本用法
<ul>
{% for user in user_list %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
2.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 user_list %}
用户人数:{{ user_list|length }}
{% elif black_list %}
黑名单数:{{ black_list|length }}
{% else %}
没有用户
{% endif %}
(四)if ...else
{% if user_list|length > 5 %}
七座豪华SUV
{% else %}
黄包车
{% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
(五)with
定义一个中间变量
{% with p_list.0.name as chenrun %}
{{chenrun}}
(六)csrf_token
这个标签用于跨站请求伪造保护。
在页面的form表单里面写上{% csrf_token %}
(七)注意事项
1. Django的模板语言不支持连续判断,即不支持以下写法:
{% if a > b > c %}
...
{% endif %}
可以写成 a>b and b>c
2. Django的模板语言中属性的优先级大于方法
def xx(request):
d = {"a": 1, "b": 2, "c": 3, "items": "100"}
return render(request, "xx.html", {"data": d})
如上,我们在使用render方法渲染一个页面的时候,传的字典d有一个key是items并且还有默认的 d.items() 方法,
此时在模板语言中: {{ data.items }} 默认会取d的items key的值。
二.母板
我们通常会在母板中定义页面专用的CSS块和JS块,方便子页面替换
(一).继承母板
在子页面中在页面最上方使用下面的语法来继承母板。
语法: {% extends 'layouts.html' %}
(二)块(block)
通过在母板中使用{% block xxx %}来定义"块"。
{% block page_panel %}
<h3 class="panel-title">出版社列表</h3>
{% endblock %}
在子页面中通过定义母板中的block名来对应替换母板中相应的内容
{% block page_panel %}
<h3 class="panel-title">书名列表</h3>
{% endblock %}
三.组件
可以将常用的页面内容如导航条,页尾信息等组件保存在单独的文件中,然后在需要使用的地方按如下语法导入即可。
{% include 'navbar.html' %}
四.静态文件相关
(一)第一种方式static
1.导入
{% load static %}
2.使用
<script src="{% static "mytest.js" %}"></script>
注意:某个文件多处被用到可以存为一个变量
{% load static %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}"></img>
(二)第二种方式 get_static_prefix
{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />
或者:
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!" />
五.自定义simpletag
类似于自定义filter,只不过接收更灵活的参数
1.在app下创建templatetags
2.在templatetags下创建mydefination.py
3.注册 simple tag
@register.simple_tag(name="plus")
def plus(a, b, c):
return "{} + {} + {}".format(a, b, c)
4.使用自定义simple tag
{% load mydefination %}
{% plus "1" "2" "abc" %}
六.inclusion_tag
多用于返回html代码片段
1.在app下创建templatetags
2.在templatetags下创建mydefination.py
3.templatetags注册 inclusion_tag
@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 {"data": data}
4.templates/result.html
<ul>
{% for choice in data %}
<li>{{ choice }}</li>
{% endfor %}
</ul>
5.templates/index.html
<body>
{% load my_inclusion %}

{% show_results 10 %}
</body>

猜你喜欢

转载自www.cnblogs.com/J-7-H-2-F-7/p/9630643.html