1.Django中内建了一些默认函数(pycharm中ctrl点击函数查看更多),可以在html中通过filter 方式调用,如:
<h1>{{ param|upper }}</h1>
<h1>{{ param|lower }}</h1>
2.三种自定义模板函数(功能)的使用场景:
filter:数据处理,需要传入1~2个参数,特别适合用在if条件后。
例1:
<h2>{{ n9|date:"Y-m-d H:i:s" }}</h2>
n9为参数一,"Y-m-d H:i:s"为参数二
例2:
n = 20
@register.filter
def mytag(value):
if value >18:
return True
else:
return False
{% if n|mytag %}
<h4>小伙子</h4>
{% else %}
<h4>少年</h4>
{% endif %}
simple_tag:参数无限制 & 适合返回文本
@register.simple_tag
def mytag2(a1, a2):
return a1 + "哈哈哈哈" + a2
<p>{% mytag2 "太卡了" "终于不用听了" %}</p>
inclusion_tag:参数无限制 & 适合返回HTML片段
@register.inclusion_tag("app01/xxxxx.html")
def xxxxx(arg):
return {"name": "大开哥", "age": 73}
xxxxx.html内容:<h1>{{ name }}--{{ age }}</h1>
使用:<p>{% xxxxx %}</p>
返回:<h1>大开哥--73</h1>
3.Django 中的模板语法可以接收的数据类型:
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def get_data(self):
return "哈哈哈哈哈"
def fetch_data():
return "我是一个函数"
def gen_data():
yield 123
yield 456
yield 789
def index(request):
context = {
"n1": "仙人掌", # 字符串
"n2": [11, 22, 33, 44], # 列表
"n3": {
"name": "武沛齐", # 字典
"age": 19,
},
'n4': [
{"id": 1, "name": "新晨1", "age": 18},
{"id": 2, "name": "新晨2", "age": 18},
{"id": 3, "name": "新晨3", "age": 18},
{"id": 4, "name": "新晨4", "age": 18},
],
"n5": Person("江春", 19), # 对象
"n6": fetch_data, # 函数
"n7": gen_data, # 生成器对象
"n9": datetime.datetime.now()
}
return render(request, 'app01/index.html', context)
取值方式:
<p>{{ n2.0 }}</p>
<p>{{ n2.1 }}</p>
<ul>
{% for e in n2 %}
<li>{{ e }}</li>
{% endfor %}
</ul>
<hr/>
<p>{{ n3.name }}</p>
<p>{{ n3.age }}</p>
<ul>
{% for k,v in n3.items %}
<li>{{ k }} = {{ v }}</li>
{% endfor %}
{% for item in n3.keys %}
<li>{{ item }}<li>
{% endfor %}
{% for item in n3.values %}
<li>{{ item }}<li>
{% endfor %}
</ul>
<hr/>
{% for info in n4 %}
<tr>
<td>{{ info.id }}</td>
<td>{{ info.name }}</td>
<td>{{ info.age }}</td>
</tr>
{% endfor %}
<hr/>
<p>{{ n5.name }}</p>
<p>{{ n5.age }}</p>
<p>{{ n5.get_data }}</p> # 注意,这里引用方法与python代码中不一样,去掉.get_data()后的括号。
<hr/>
<p>{{ n6 }}</p>
<hr/>
<p>{{ n7 }}</p> # 取到的是生成器对象
<ul>
{% for item in n7 %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<hr/>
<h2>{{ n9 }}</h2>
<h2>{{ n9|date:"Y-m-d H:i:s" }}</h2>
4.模板语法中的注意点
inclusion_tag和include方式都可以引入html片段,但是inclusion_tag是渲染好后再传入,include方式是传入后再渲染。