模板
在Templates中添加母版:
- 母版...html
母版(master.html)中可变化的地方加入:
{%block content%}{%endblock%}
在子版 (usermg.html) 中设置如下:
{% extends 'master.html' %} {% block content%} <h1>用户管理</h1> {%end block%}
导入小组件的模块:
{% include 'model.html' %} #同样会载入model.html中的模板语言
自定义模板语言函数simple_tag:
{{ name|lower}} #lower函数让name全部小写
新建templatetags文件夹,创建函数文件xxxx.py:
from django import template from django.utils.safestring import mark_safe register = template.Library()
(1)simple_tag (不能作为if条件,参数任意)
@register.simple_tag def func_test(a): return a
在html中引入:
{% load xxxx %} {% func_test a %}
(2)filter(可以作为if条件,参数只能最多两个,不能有空格)
@register.filter def func_test1(a,b): #只能传两个参数 return a+b
在html中引入:
{% load xxxx %} {{ "maliya"|func_test1:'sasa' }} #不能有多余的空格 {{参数1|函数名:参数2}}
应用:
filter 可以放入 if 中作为条件
{%if "maliya"|func_test1:'sasa' %}
总结:
a.创建templatetags目录
b.任意py文件
c.创建template对象 register
d.定义函数,加上装饰器
e.在settings注册当前app
f.在顶部LOAD {% load xxoo%}
g.引用 {% 函数名 参数1 参数2 %}
ps:让字符串强制转化为html语言:
{{page_str|safe}} page_str = mark_safe(page_str)
分页(自定义的分页)
简单思路如下:
让字符串强制转化为html语言: {{page_str|safe}} page_str = mark_safe(page_str) 计算页数: all_count = len(LIST) count,y = divmod(all_count,10) count = count+1 if y list = [] for i in range(1,count+1): temp = '<a class = 'page' href = 'user/?p=%s'> %s </a>'%(i,i) list.append(temp) 当前页:current_page 总页数:total_page 每页显示10条数据:per_page_page 页码:11 如果:总页数 < 11 start_page = 1 end_page = total_page else: 当前页 <= 6: start_page = 1 end_page = 11 + 1 else: start_page = 当前页 -5 end_page = 当前页 +5+1 如果 当前页 +5 > 总页数: end_page = 总页数 start_page = 总页数 -10
utils文件夹:分页模块