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

  view.py中的代码:

 from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
user_list = [
{'name': 'xiao wang', 'age': ''},
{'name': 'hua hua', 'age': ''}
]
user = {'name': 'hua hua', 'age': '', 'sex': 'male'}
class Person(object):
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex def say(self):
return 'I am ' + self.name
user1 = Person('Tom', 23, 'male')
book_list = ['python', 'java', 'php'] def say(request):
return render(request, 'index.html', {'title': 'my page', 'user': user, 'book_list': book_list})

  index.html中的代码

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>hello {{ user.name }}</h1>
<li>age:{{ user.age }}</li>
<li>sex:{{ user.sex }}</li>
<div>the {{ user.name }} sya: {{ user.say }}</div>
{{ book_list.0 }}
###################
{% if user %}
<li>name: {{ user.name }}</li>
{% else %}
用户不存在
{% endif %} {% for foo in book_list %}
<li> {{ foo }}</li>
{% endfor %} {% for k, v in user.items %}
<li> {{ forloop.counter }}.{{ k }}: {{ v }}</li>
{% endfor %} </body>
</html>

  结果显示

Django运算符表达式-LMLPHP

05-11 17:13