[Django模板系统]在视图中使用模板
2015-10-19 23:23
851 查看
注:以下内容转载自
现代魔法学院 网站的 Django实践:在视图中使用模板 一文,仅供学习使用。
前面讲了这么多理论的东西,都快受不了了吧。那么这里先不讲模板的规则机制什么的,我们来动手写一个模板的例子,实践一下,有不懂再回去继续讲规则。
1. 定义你的 templates 目录
去 settings.py 这个文件,配置 templates 目录:
2. 编写 template 文件 current_datetime.html
3. 编写 views 层的 def
4. 设定 urls.py 的路径
OK,我们打开 http://127.0.0.1:8000/time2/,成功,页面显示:
就这么简单。
现代魔法学院 网站的 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
就这么简单。
相关文章推荐
- 一个设计师眼中的Google: 宇宙里最值钱的一个偶然
- golang.org 不能访问
- 分治-二叉树重建
- 区间DP-矩阵连乘问题
- LabyrinthAlgorithm
- Google Guava Collections 使用介绍
- Mongo基本操作和命令
- django 使用记录 mac
- django自定义上传文件路径
- Google APAC 2016 University Graduates Test Round C解题报告
- 国内 google depot_tools gclient SSLError hostname 错误解决
- Codeforces 588 A. Duff and Meat
- Django学习笔记(一)
- go git 安装配置与使用 (windows 7 64bit)
- django 画图
- 让Category支持添加属性与成员变量【转载】
- Codeforces 574 A. Bear and Elections
- 寻找中位数
- 2014 Google IO 惊喜
- GOOD BLOG URL