1.RequestContext和Context处理器
views.py
from django.http import HttpResponse from django.template import loader, Context def view_1(request): t = loader.get_template('app.html') #创建Template对象 c = Context({ #创建Context对象 'app': 'My app', 'user': 'a', 'ip_address': 'b', 'message': 'I am view 1.' }) html = t.render(c) #调用render()方法 return HttpResponse(html)
urls.py
from books import views (r'^context/$', views.view_1)
app.html
`app` `user` `ip_address` `message`
访问http://192.168.1.22/context/运行结果
My app a b I am view 1.
2.三种方式实现相同的输出
views.py
from django.http import HttpResponse #def current_datetime(request): # now = datetime.datetime.now() # html = "<html><body>It is now %s.</body></html>" % now # return HttpResponse(html) #def current_datetime(request): # now = datetime.datetime.now() # t = get_template('current_datetime.html') # html = t.render(Context({'current_date':now})) #return HttpResponse(html) def current_datetime(request): now = datetime.datetime.now() return render_to_response('dataapp/current_datetime.html',{'current_date':now})
urls.py
from books import views (r'^time/$',current_datetime),
current_datetime.html
{% extends "base.html" %} {% block title %} The current time {% endblock %} {% block content %} <p> It is now{{ current_date }}.</p> {% endblock %}
访问结果
3.模板描述了向某个与公司签单人员致谢的HTML页面
views.py
def order(request): t = loader.get_template('order.html') c = Context({'person_name': 'John Smith', 'company': 'JD', 'ship_date': datetime.date(2009, 4, 2), 'ordered_warranty': True}) html = t.render(c) return HttpResponse(html)
urls.py
(r'^order/$', views.order)
order.html
<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><b>Here are the items you've ordered:</b></p> <ul> {% for item in item_list %} <li>{{ item }}</li> {% endfor %} </ul> <canvas id="myCanvas" width="170" height="50" style="border:1px solid #c3c3c3;"> Your browser does not support the canvas element. </canvas> <script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); var grd=cxt.createLinearGradient(0,0,175,50); grd.addColorStop(0,"#FF0000"); grd.addColorStop(1,"#00FF00"); cxt.fillStyle=grd; cxt.fillRect(0,0,175,50); </script> {% 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> <form action="/time/" method="post"> <p>Subject: <input type="text" name="subject"></p> <p>Your e-mail (optional): <input type="text" name="email"></p> <p>Message: <textarea name="message" rows="10" cols="50"></textarea></p> <input type="submit" value="Submit"> </form> </body> </html>
访问结果
点击Submit按钮跳转到http://192.168.1.22/time/页面
5.html内容写在Template
views.py
from django.template import Context,Template def weekend(request): t = Template('<html><body>{% if not today_is_weekend %}<p>{{ Name }},Welcome to the weekend!</p>{% endif %}</html></body>') c = Context({'Name':'Allen'}) html = t.render(c) return HttpResponse(html)
访问结果:
5.自定义标签和过滤器
views.py
def dragon(request): return render_to_response('dragon.html')
urls.py
(r'^dragon/$', views.dragon)
myNewLibrary.py
import datetime from django import template register = template.Library() @register.filter(name='remove') def remove(var,arg): return var.replace(arg, '') @register.filter def lower(value): "Converts a string inot all lowercase" return value.lower() @register.tag(name='current_time') def do_current_time(parser, token): try: tag_time, format_string = token.split_contents() except ValueError: msg = '%r tag requires a single argument' % token.split_contents()[0] raise template.TemplateSyntaxError(msg) return CurrentTimeNode(format_string[1:-1]) class CurrentTimeNode(template.Node): def __init__(self, format_string): self.format_string = str(format_string) def render(self, context): now = datetime.datetime.now() return now.strftime(self.format_string)
dragon.html
<html> <head> <title></title> </head> <body> {% load myNewLibrary %} <p>The time is {% current_time "%Y-%m-%d %I:%M %p" %}.</p> </body> </html>
访问结果: