很多时候,我们要将后台处理的数据回显到页面上,显然用纯静态的html不可能实现,需要与一种模板语言结合,来实现动态回显,在django中内置有这样的动态模板,比如我们之前的hello world,我们可以如下改造:
from django.http import HttpResponse
from django.template import Context, Template
def hello(request):
t = Template("hello {{ name }}")
c = Context({"name": "world"})
return HttpResponse(t.render(c))
先创建一个模板,这个模板里会有一个变更name,然后在模板数据里放入一个key为name,value为world的对象。然后执行t.render(c)来将模板渲染好,最终显示hello world
一般在web开发中,我们会将所有的模板文件放到一个地方,然后将后台处理好要回显的数据放到context中,然后将最终将二者渲染好,返回给浏览器显示。我们可以将不同页面的模板放在不同的文件里,通过一个接口取得这个文件,然后生成一个template。
比如我们在mysite下建一个文件夹template,存放一个hello.html文件,然后hello.html的内容即为:"hello {{ name }}"。要取到这个文件的生成模板,首先我们要在settings.py中设置TEMPLATE_DIR的值,找到TEMPLATE_DIR配置的地方,加上一行指定template路径,如下:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"PATH/template",
)
然后我们就可以将原来的views.py文件改为如下来显示内容:
from django.http import HttpResponse
from django.template import Context, Template, loader
def hello(request):
t = loader.get_template("hello.html")
c = Context({"name": "world"})
return HttpResponse(t.render(c))
其它的或者可以通过loader下的render_to_string函数来执行,如下:
from django.http import HttpResponse
from django.template.loader import render_to_string
def hello(request):
html=render_to_string('hello.html', { 'name': 'world' })
return HttpResponse(html)
动态模板语言学习详见: https://docs.djangoproject.com/en/1.4/topics/templates/