您的位置:首页 > 编程语言 > Go语言

[Django模板系统]在视图中使用模板

2015-10-19 23:23 851 查看
注:以下内容转载自
现代魔法学院 网站的 Django实践:在视图中使用模板 一文,仅供学习使用。

前面讲了这么多理论的东西,都快受不了了吧。那么这里先不讲模板的规则机制什么的,我们来动手写一个模板的例子,实践一下,有不懂再回去继续讲规则。

1. 定义你的 templates 目录

去 settings.py 这个文件,配置 templates 目录:

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.
'E:/PythonProject/templates',
)


2. 编写 template 文件 current_datetime.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>简明现代魔法 on Python Django</title>
</head>

<body>

<p>现在的时间是 {{ current_date }}.</p>
<p>简明现代魔法 on Python Django</p>

</body>

</html>


3. 编写 views 层的 def

from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime

def current_datetime_template(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)


4. 设定 urls.py 的路径

from django.conf.urls.defaults import *
from PythonProject.views import current_datetime_template

urlpatterns = patterns('',

('^time2/$', current_datetime_template),
)


OK,我们打开 http://127.0.0.1:8000/time2/,成功,页面显示:
现在的时间是 July 24, 2013, 2:34 p.m..
简明现代魔法 on Python Django


就这么简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: