读书笔记:Django 模板开发(三)Context详解
来源:互联网 发布:讯飞大数据开发平台 编辑:程序博客网 时间:2024/05/02 20:20
Context的本质就是一组用字典封装好的准备送给template的参数,在view和template中扮演桥梁的角色。
作为面向对象的程序,传递的参数不仅仅是简单的变量还可以是class等,
>>> # Create a class with a single method>>> class Favorite():>>> def get_color(self):>>> return 'blue'>>>>>> favorite = Favorite()>>> c = Context({'favorite': favorite })>>> t = Template('My favorite color is {{ favorite.get_color }}.')>>> print t.render(c)My favorite color is blue.
>>> color_list = ['orange', 'blue', 'green', 'red']>>> c = Context({ 'favorite_colors': color_list })>>> t = Template("My favorite color is {{ favorite_colors.0 }}.")>>> print t.render(c)My favorite color is orange.
当然你也可以显式的禁止在template运行函数 wipeout.alters_data = True,但是这样的行为比较不推荐,除非是特别简单的比如get set之类的,因为这样就破坏了数据和逻辑分离的结构。
另外django还提供了一个函数locals(),就是把当前环境里的变量都拉一起组成一个字典送给template,貌似很方便,但是越望后期这样的做法越不可取,因为会添加一些不是必须的内容,比较影响效率。
template的调试:
调式的基本思想还是导入debug相关的context, 系统会默认写好一些常用的global的context,另外我们自己也可以定义global的context。
下面两行是调试的几本代码,分为两部分,第一是配置,第二是导入函数。
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
)
c = RequestContext(request, {'press': p}) 用来代替常用的Context函数
1) 使用auth的Context,他自动提供了user, messages, perms,这样提供了一些全局的debug信息
2)使用debug变量
{% if debug %} {% for query in sql_queries %} <p>This query took {{ query.time }} seconds: {{ query.sql }}</p> {% endfor %}{% endif %}3) 使用media,抽出一些共同的url的部分
- 读书笔记:Django 模板开发(三)Context详解
- 读书笔记:Django 模板开发(一)template概述
- Django(三)模板
- 读书笔记:Django 模板开发(四) 后续总结
- PythonWeb开发Django框架(三)模板Templates初步
- 读书笔记:Django 模板开发(二)Views, URLs, and Generic Views
- django template 基础(模板对象(Template),上下文对象(Context))
- Django系列三:Django 模板
- Django学习(三)模板定制
- 千与千寻django(三)---django的模板系统
- (三)详解Servlet-读书笔记
- django开发(7)使用模板
- django 学习 (三) 模板变量
- Django技术详解(三)配置URL
- django开发电子商城(三)django内置分页
- Django模板系统详解(四)
- (读书笔记)mybatis (三)-----environments详解
- 《Android 开发艺术探索》读书笔记三 Intent和IntentFilter详解
- java基于svnkit Api的开发
- struts2的JSP页面方法输出
- Android的硬件加速
- 批量重命名
- iOS7新特征汇总[02]:游戏、地图以及AirDrop
- 读书笔记:Django 模板开发(三)Context详解
- GM(1,1)模型
- 一些复习笔记
- unity3d 调试
- iOS7新特征汇总[01]:UI和多任务增强
- ORA-00600 internal error code,arguments
- android之activity切换
- struts2 validate,hibernate validate,struts2-fullhibernatecore-plugin-2.2.2-GA.jar
- ubuntu下交叉编译器的切换