前面的例子中,我们是直接将HTML写在了Python代码中,这种写法并不可取。我们需要使用模板技术将页面设计和Python代码分离。
模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。
参考http://djangobook.py3k.cn/2.0/chapter04/,对以下例子模板:
<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>
在Python代码中使用Django模板的最基本方式如下:
例子如下:
>>> from django import template
>>> t = template.Template('My name is {{ name }}.')
>>> c = template.Context({'name': 'Adrian'})
>>> print t.render(c)
My name is Adrian.
>>> c = template.Context({'name': 'Fred'})
>>> print t.render(c)
My name is Fred.
我们先给我们的testapp添加一个add视图,即在views.py
中添加:
def add(request):
return render(request, 'add.html')
在testapp目录下新件一个templates文件夹,里面新建一个add.html。默认情况下,Django会默认找到app目录下的templates文件夹中的模板文件。
然后在add.html
中写一些内容:
<!DOCTYPE html>
<html>
<head>
<title>欢迎光临</title>
</head>
<body>
Just Test
</body>
</html>
更新url配置,即在urls.py中添加:
from testapp.views import add
urlpatterns = [
......
url(r'^add/$', add),
]
重启服务后便可以访问http://127.0.0.1:8000/add/
。
接下来尝试在html文件中放入动态内容。
views.py:
def add(request):
string = "这是传递的字符串"
return render(request, 'add.html', {'string': string})
即向add.html传递一个字符串名称为string。在字符串中这样使用:
add.html
{{ string }}
修改views.py:
def add(request):
testList = ["Python", "C++", "JAVA", "Shell"]
return render(request, 'add.html', {'testList': testList})
修改add.html:
{% for i in testList %}
{{i}}
{% endfor %}
修改views.py:
def add(request):
testDict = {"1":"Python", "2":"C++", "3":"JAVA", "4":"Shell"}
return render(request, 'add.html', {'testDict': testDict})
修改add.html:
{% for key,value in testDict.items %}
{{key}} : {{value}}
{% endfor %}
更多有用的操作可以参考https://code.ziqiangxuetang.com/django/django-template2.html
原文:https://www.cnblogs.com/xl2432/p/10495801.html