1.RequestContext和Context处理器
views.py
from django.http import HttpResponsefrom django.template import loader, Contextdef 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`
访问
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 = "It is now %s." % 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 %}It is now{
{ current_date }}.{% 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
Ordering notice Ordering notice
Dear {
{ person_name }},Thanks for placing an order from {
{ company }}. It's scheduled toship on { { ship_date|date:"F j, Y" }}.Here are the items you've ordered:
- {% for item in item_list %}
- { { item }} {% endfor %}
访问结果
点击Submit按钮跳转到页面
5.html内容写在Template
views.py
from django.template import Context,Templatedef weekend(request): t = Template('{% if not today_is_weekend %}{
{ Name }},Welcome to the weekend!{% endif %}') 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 datetimefrom django import templateregister = template.Library()@register.filter(name='remove')def remove(var,arg): return var.replace(arg, '')@register.filterdef 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
{% load myNewLibrary %} The time is {% current_time "%Y-%m-%d %I:%M %p" %}.
访问结果: