作者:jeffjie

题目要求

写一个Hello,template程序,使用模板来显示Hello,{name},其中name是变量,要由外部传入

框架说明

Django (http://djangoproject.com)

步骤

本节内容沿用上一节,在本节将不再重复描述创建项目及应用的过程。 在这里,还是使用已有的helloworld.hello应用,在此基础上增加一个模板的view。

创建模板hello.html

Django的应用会跑到其目录下的templates目录下面去寻找模板,默认情况下,我们需要在应用目录创建templates目录,并在下面创建模板。

cd helloworld
cd hello
mkdir templates
cd templates
vi hello.html

为hello.html添加内容,Django模板语法里,显示变量值的写法是变量名

<CTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <title>Hello World</title>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Hello, {{name}}</h1>
</body>
</html>

在helloworld/hello/views.py增加一个方法

from django.shortcuts import render_to_response
def template(request):
    return render_to_response('hello.html',{'name':'template'})

配置helloworld/urls.py

加入下面这行代码:

(r'^template/$','helloworld.hello.views.template'),

测试

python manage.py runserver

访问 http://localhost:8000/template 即可。

DjangoHelloTemplate (last edited 2009-12-25 07:16:01 by localhost)