创建模板对象
Template类在django.template模板中
// 用django-admin.py startproject 命令创建一个项目目录
django-admin.py startproject django_template
// 进入目录
cd django_template
// 启动交互界面
python manage.py shell
// 在命令行输入下面三条(不用输入>>>)
>>> from django.template import Template
>>> t = Template("My name is {{ name }}.")
>>> print t
背景变量的查找
>>> from django.template import Template, Context
>>> person = {‘name‘: ‘Sally‘, ‘age‘: ‘43‘}
>>> t = Template(‘{{ person.name }} is {{ person.age }} years old.‘)
>>> c = Context({‘person‘: person})
>>> t.render(c)
‘Sally is 43 years old.‘
下例使用了一个自定义类:
>>> from django.template import Template, Context
>>> class Person(object):
... def __init__(self, first_name, last_name):
... self.first_name, self.last_name = first_name, last_name
>>> t = Template(‘Hello, {{ person.first_name }} {{ person.last_name }}.‘)
>>> c = Context({‘person‘: Person(‘John‘, ‘Smith‘)})
>>> t.render(c)
‘Hello, John Smith.‘
命令行界面很好用:
句点也可用于访问列表索引,例如:
>>> from django.template import Template, Context
>>> t = Template(‘Item 2 is {{ items.2 }}.‘)
>>> c = Context({‘items‘: [‘apples‘, ‘bananas‘, ‘carrots‘]})
>>> t.render(c)
‘Item 2 is carrots.‘
模板系统一个经典实例(html和python分离的):
项目目录:MyDjangoSite
https://github.com/liuqiuchen/django
修改settings.py,加上templates的路径
TEMPLATES = [ { ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘, ‘DIRS‘: [ # 添加templates路径 BASE_DIR+"/templates", ], ‘APP_DIRS‘: True, ‘OPTIONS‘: { ‘context_processors‘: [ ‘django.template.context_processors.debug‘, ‘django.template.context_processors.request‘, ‘django.contrib.auth.context_processors.auth‘, ‘django.contrib.messages.context_processors.messages‘, ], }, }, ]
新建view.py
from django.shortcuts import render_to_response def user_info(request): name = ‘zbw‘ age = 24 #t = get_template(‘user_info.html‘) #html = t.render(Context(locals())) #return HttpResponse(html) return render_to_response(‘user_info.html‘, locals()) # 加locals()才能显示模板数据
添加url:
urls.py
from django.conf.urls import url from django.contrib import admin from MyDjangoSite.view import user_info urlpatterns = [ url(r‘^u/$‘,user_info), url(r‘^admin/‘, admin.site.urls), ]
模板文件:
templates/user_info.html
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>用户信息</title> </head> <body> <h3>用户信息:</h3> <p>姓名:{{name}}</p> <p>年龄:{{age}}</p> </body> </html>