码迷,mamicode.com
首页 > 其他好文 > 详细

django入门之模板的用法

时间:2017-01-04 21:34:53      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:blocks   ext   .sh   获取   需要   rom   浏览器   rac   添加   

1.为什么要使用模板?

  看下以前的代码

技术分享
1 #-*- coding:utf-8 -*-
2 from django.shortcuts import render
3 from django.http import HttpResponse
4 # Create your views here.
5 
6 def index(request):
7     return HttpResponse(t.render("<h1>Hello,World!</h1>"))
View Code

 这里是把页面以字符串的形式返回。如果页面有点多,页面内容有点多的话,就得返回写好的html网页了。

2. 使用写好的网页。

  首先得引入django的模板加载器,代码如下:

1 from django.template import loader,Context

   然后要创建一个加载器,和一个返回动态数据的Context对象,最后返回个模板。

技术分享
1 def index(request):
2     t = loader.get_template("index.html")
3     c = Context({"title":"django模板添加动态数据"})
4     return HttpResponse(t.render(c))
View Code

3. 创建模板。然后在你的app文件夹下,也就是和你的views.py同级目录下新建个文件夹templates,并在templates文件夹下创建个html文件,这里叫index.html

4. 编辑模板。打开index.html,随意输入点html代码

技术分享
1 <html>
2     <body>
3       <h1>Hello,django!</h1>
4     </body>
5 </html>    
View Code

 最后你可以运行服务器,在cmd中打开项目目录,输入命令:manage.py runserver 或者 python manage.py runserver,

然后你会看到如下界面:

技术分享

你可以打开你的浏览器,在导航栏中输入地址:http://127.0.0.1:8000/blog/index ,blog是指你的应用名,我的是blog。然后你就可以看到你的index.html了。

5. 在模板里获取动态数据

  打开index.html的编辑界面,在需要输出的地方加上{{需要输出的变量}}。比如我上面的代码里传入了title,在html里只要写{{title}}就行了

1 <title>Hello,{{title}}</title>

 

django入门之模板的用法

标签:blocks   ext   .sh   获取   需要   rom   浏览器   rac   添加   

原文地址:http://www.cnblogs.com/sunchang/p/6250239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!