[举重若轻]python+django+mysql web开发入门学习之动态模板
来源:互联网 发布:大连软件职业学院官网 编辑:程序博客网 时间:2024/04/30 01:12
很多时候,我们要将后台处理的数据回显到页面上,显然用纯静态的html不可能实现,需要与一种模板语言结合,来实现动态回显,在django中内置有这样的动态模板,比如我们之前的hello world,我们可以如下改造:
from django.http import HttpResponsefrom django.template import Context, Templatedef hello(request): t = Template("hello {{ name }}") c = Context({"name": "world"}) return HttpResponse(t.render(c))
先创建一个模板,这个模板里会有一个变更name,然后在模板数据里放入一个key为name,value为world的对象。然后执行t.render(c)来将模板渲染好,最终显示hello world
一般在web开发中,我们会将所有的模板文件放到一个地方,然后将后台处理好要回显的数据放到context中,然后将最终将二者渲染好,返回给浏览器显示。我们可以将不同页面的模板放在不同的文件里,通过一个接口取得这个文件,然后生成一个template。
比如我们在mysite下建一个文件夹template,存放一个hello.html文件,然后hello.html的内容即为:"hello {{ name }}"。要取到这个文件的生成模板,首先我们要在settings.py中设置TEMPLATE_DIR的值,找到TEMPLATE_DIR配置的地方,加上一行指定template路径,如下:
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. "PATH/template",)
然后我们就可以将原来的views.py文件改为如下来显示内容:
from django.http import HttpResponsefrom django.template import Context, Template, loaderdef hello(request): t = loader.get_template("hello.html") c = Context({"name": "world"}) return HttpResponse(t.render(c))
其它的或者可以通过loader下的render_to_string函数来执行,如下:
from django.http import HttpResponsefrom django.template.loader import render_to_stringdef hello(request): html=render_to_string('hello.html', { 'name': 'world' }) return HttpResponse(html)
动态模板语言学习详见:https://docs.djangoproject.com/en/1.4/topics/templates/
- [举重若轻]python+django+mysql web开发入门学习之动态模板
- [举重若轻]python+django+mysql web开发入门学习之orm
- [举重若轻]python+django+mysql web开发入门学习之环境搭建
- [举重若轻]python+django+mysql web开发入门学习之hello world
- Python Web开发:Django入门学习笔记(1)
- Python Web开发:Django入门学习笔记(2)
- python web开发--Django 学习
- python web开发之django
- python之web开发1:Eclipse+PyDev+Django+Mysql搭建Python web开发环境
- 【python】Django web应用开发入门
- python web开发——Django入门
- Python web入门:Django学习与实践二(简单页面实现和创建一个模板)
- Python Web开发 之Django框架入门学习笔记(一)——安装和初步使用
- Python学习二:Django Web入门
- python学习之浅谈django模板
- Python Web开发之Django环境搭建
- python web开发框架 - 之 Django Request
- Python Web开发Django、Flask之Templates
- Installutil.exe的位置和路径
- Sql server 的update语句的新认识
- 如何理解extract_options!
- 如何说服别人,如何让别人理解自己
- C# 将bit流转化为十六进制显示出来
- [举重若轻]python+django+mysql web开发入门学习之动态模板
- svn入门续-1
- Mysql双主自增长冲突处理
- MSSQL2008下查看结构变化监控,Schema Change History
- 黑马程序员__JAVA基础加强--类加载器和代理总结
- elasticsearch集群监控工具bigdesk
- Spring MVC 教程,快速入门,深入分析
- hibernate 联合主键
- Unix命令行程序和内建指令