上一节中的输入,即视图中的return HttpResponse()部分。函数中的内容为<html><body>……

意思就是,前端文件,要每次都要手写,打印,这非常麻烦。通常,它会包括很多内容,还有js文件,css文件等。而且设计页面也不好设计,或者设计好了,再粘贴html字串,进行输出。且会发现html代码与python后台代码掺杂在一起。

通过自定义,

直接在视图中写。新建立视图(函数)hello_who如下:

def hello_who(request):

    t=template.Template('hello {{name}}')

    c=template.Context({'name':'宋江'})

    return HttpResponse(t.render(c))

 

通过创建模板,输出hellowho

这里who的名字为中文的宋江。,如果在页面中正常显示中文,需要在settings.py中设置LANGUAGE_CODE = 'zh-cn'

且在视图文件views.py中,第一行加入#encoding=utf-8

使用模板

先建立模板文件,文件名任意。模板文件就是html前台文件。与aspx页类似。先建立一个hello.html文件。如下:

<html>

<body>

<div style="color:red;"><b>Hello,{{name}}</b></div>

</body>

</html>

然后在视图中加载这个模板,并给变量赋值。

视图hello_who改为:

def hello_who(request):

    t = get_template('hello.html')

    html = t.render(Context({'name': '宋江'}))

return HttpResponse(html)

其中,获得模板,和呈现函数,可以利用一个函数实现,如下:
def hello_who(request):

    return render_to_response('hello.html', {'name': '宋江'})

 

另使用这个函数,需要引入:

from django.shortcuts import render_to_response

通过locals()返回所有定义的映射

def hello_who(request):

    name= '宋江'

    return render_to_response('hello.html', locals())

posted on 2013-04-21 16:27  梅桦  阅读(948)  评论(0编辑  收藏  举报