Django模板
变量
1.变量名由字母数字和下划线组成
2.点(.)在模板语言中有特殊的含义,用来获取对象的相应属性值
from django.shortcuts import render
def template_test(request):
l = [11, 22, 33]
d = {"name": "alex"}
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def dream(self):
return "{} is dream...".format(self.name)
Alex= Person(name="Alex", age=34)
Egon = Person(name="Egon", age=90)
Eva = Person(name="Eva", age=34)
person_list = [Alex, Egon, Eva]
return render(request, "template_test.html", {"l": l, "d": d, "person_list": person_list}
html模板支持的写法
{# 取l中的第一个参数 #}
{{ l.0 }}
{# 取字典中key的值 #}
{{ d.name }}
{# 取对象的name属性 #}
{{ person_list.0.name }}
{# .操作只能调用不带参数的方法 #}
{{ person_list.0.dream }}
当templates引擎遇到变量时,引擎使用变量的值代替变量。使用(.)访问变量的属性,比如{{d.name}}。当templates引擎遇到(.)的时候,会按照如下顺序查找:
1.字典查找,例如:foo[‘bar’]
2.属性查找,例如:foo.bar
3.方法查找,例如:foo.bar()
4.list-index查找,例如foo[bar]
模板的大致结构(后面有详细)
Django的templates(templates:模板),它是一个string文本。templates用来分离一个文档的表现形式和内容(也可以说成数据)。templates定义了placeholder(placeholder:占位符)和表示多种逻辑的tags(tags:标签)来规定文档如何展现。通常templates用来输出HTML,但是Django的templates也能生成其他基于文本的形式。
<html>
<head><title>Ordering notice</title></head>
<body>
<h1>Ordering notice</h1>
<p>Dear {{ person_name }},</p>
<p>Thanks for placing an order from {{ company }}. It's scheduled to
ship on {{ ship_date|date:"F j, Y" }}.</p>
<p>Here are the items you've ordered:</p>
<ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% if ordered_warranty %}
<p>Your warranty information will be included in the packaging.</p>
{% else %}
<p>You didn't order a warranty, so you're on your own when
the products inevitably stop working.</p>
{% endif %}
<p>Sincerely,<br />{{ company }}</p>
</body>
</html>
标签
一、if/else标签
只能判断True和False
{% if %}标签会考察一个变量,如果这个变量为真(存在),系统会显示在 {% if %} 和 {% endif %} 之间的任何内容
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% endif %}
{% else %} 标签是可选的:
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% else %}
<p>Get back to work.</p>
{% endif %}
{% if %} 标签接受 and , or 或者 not 关键字来对多个变量做判断 ,或者对变量取反( not ),但不允许在同一个标签中同时使用 and 和 or ,因为逻辑上可能模糊的。
二、for标签
for标签用于迭代序列中的各个元素。
与 Python 的 for 语句类似,语法是for X in Y。其中 Y 是要迭代的序列, X 是单次循环中使用的变量。每次迭代时,模板系统会渲染 {% for %} 和 {% endfor %} 之间的内容。