Django运算符表达式

  在html页面中,加入运算符表达式,进行逻辑判断。可参考手册。我用的Django是2.1版本

  view.py中的代码:

 1 from django.shortcuts import render
 2 from django.http import HttpResponse
 3 # Create your views here.
 4 user_list = [
 5     {'name': 'xiao wang', 'age': '18'},
 6     {'name': 'hua hua', 'age': '20'}
 7 ]
 8 user = {'name': 'hua hua', 'age': '20', 'sex': 'male'}
 9 class Person(object):
10     def __init__(self, name, age, sex):
11         self.name = name
12         self.age = age
13         self.sex = sex
14 
15     def say(self):
16         return 'I am ' + self.name
17 user1 = Person('Tom', 23, 'male')
18 book_list = ['python', 'java', 'php']
19 
20 def say(request):
21     return render(request, 'index.html', {'title': 'my page', 'user': user, 'book_list': book_list})

  index.html中的代码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>{{ title }}</title>
 6 </head>
 7 <body>
 8 <h1>hello {{ user.name }}</h1>
 9 <li>age:{{ user.age }}</li>
10 <li>sex:{{ user.sex }}</li>
11 <div>the {{ user.name }} sya: {{ user.say }}</div>
12 {{ book_list.0 }}
13 ###################
14 {% if user %}
15     <li>name: {{ user.name }}</li>
16 {% else %}
17 用户不存在
18 {% endif %}
19 
20 {% for foo in book_list %}
21     <li> {{ foo }}</li>
22 {% endfor %}
23 
24 {% for k, v in user.items %}
25     <li> {{ forloop.counter }}.{{ k }}: {{ v }}</li>
26 {% endfor %}
27 
28 </body>
29 </html>

  结果显示

 

posted @ 2017-11-01 21:14  今夜无风  阅读(1223)  评论(0编辑  收藏  举报