模板
前面的例子中,咱们是直接将HTML写在了Python代码中,这种写法并不可取。咱们须要使用模板技术将页面设计和Python代码分离。html
模板一般用于产生HTML,可是Django的模板也能产生任何基于文本格式的文档。django
参考http://djangobook.py3k.cn/2.0/chapter04/,对如下例子模板:app
<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>
- 用两个大括号括起来的文字(例如 {{ person_name }} )被成为变量。意味着在此处插入指定变量的值。
- 被大括号和百分号包围的文本(例如 {% if ordered_warranty %} )是模板标签,通知模板系统完成耨写工做的标签。这个例子中有包含if和for两种标签。
- if标签就是相似Python中的if语句;而for标签就是相似Python中的for语句。
- 这个例子中还使用了filter过滤器((例如 {{ ship_date|date:"F j, Y" }}),它是一种最便捷的转换变量输出格式的方式。
使用模板系统
在Python代码中使用Django模板的最基本方式以下:url
- 能够用原始的模板代码字符串建立一个 Template 对象;
- 调用模板对象的render方法,而且传入一套变量context。模板中的变量和标签会被context值替换。
例子以下:spa
>>> 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
中添加:.net
def add(request): return render(request, 'add.html')
在testapp目录下新件一个templates文件夹,里面新建一个add.html。默认状况下,Django会默认找到app目录下的templates文件夹中的模板文件。设计
而后在add.html
中写一些内容:code
<!DOCTYPE html> <html> <head> <title>欢迎光临</title> </head> <body> Just Test </body> </html>
更新url配置,即在urls.py中添加:orm
from testapp.views import add urlpatterns = [ ...... url(r'^add/$', add), ]
重启服务后即可以访问http://127.0.0.1:8000/add/
。htm
接下来尝试在html文件中放入动态内容。
显示一个基本的字符串在网页上。
views.py:
def add(request): string = "这是传递的字符串" return render(request, 'add.html', {'string': string})
即向add.html传递一个字符串名称为string。在字符串中这样使用: add.html
{{ string }}
使用for循环显示list
修改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