读书笔记: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的部分





原创粉丝点击