[django]document_translation

希望大家可以在评论中帮忙指出错误,这文是 用来翻译如下链接的。 

https://docs.djangoproject.com/en/1.3/ref/templates/api/

The Django template language: For Python programmers

This document explains the Django template system from a technical perspective – how it works and how to extend it. If you’re just looking for reference on the language syntax, see The Django template language.

If you’re looking to use the Django template system as part of another application – i.e., without the rest of the framework – make sure to read the configuration section later in this document.

 

 

Django 模板语言:给pytho程序员

此文档阐释django模板系统的技术性观点——如果工作及如何扩展它。如果你只想参考语言语法,请查看……

如果你正在寻找在别的程序中使用django模板系统的使用方法——换言之,没有framework的部分-请你确保在本文档之后阅读configuration节。

 

Basics

template is a text document, or a normal Python string, that is marked-up using the Django template language. A template can contain block tags or variables.

block tag is a symbol within a template that does something.

This definition is deliberately vague. For example, a block tag can output content, serve as a control structure (an “if” statement or “for” loop), grab content from a database or enable access to other template tags.

Block tags are surrounded by "{%" and "%}".

Example template with block tags:

{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}

variable is a symbol withpastingin a template that outputs a value.

Variable tags are surrounded by "{{" and "}}".

Example template with variables:

My first name is {{ first_name }}. My last name is {{ last_name }}.

context is a "variable name" -> "variable value" mapping that is passed to a template.

A template renders a context by replacing the variable "holes" with values from the context and executing all block tags.

基础:模板是使用django模板语言标记的一个文本文档,或者是普通的python字符串。模板可以含有BLOCK TAGS或VARIABLES(模板可以含有块标记或变量值) 一个块标记是一个在模板内表示 要做什么 的记号。

 

 这个定义是含糊的.例如,一个块标记可以输出内容、提供控制结构(如使用if 声明或for循环)、从数据库或其他可以允许访问的模板标记获取内容。

块标记使用"{%"和"%} "进行包围。

一个在模板中使用块标记的实例:

        ===============实例============

变量就是在模板中的一个用于输出值的标记。

变量标记使用"{{"和"}}" 包围。

示例:

----------------------示例=============

 内容是通过 “变量名”->“变量值” 的映射在模板中传递的。

 模板 通过 值 替换 变量 的 "坑" 和执行所有块标记来 呈递一个上下文。

备注========================

 单词翻译:

 technical perspective

技术性观点
reference 
参考
rest
其余部分
contain 
包含,含有
tag
标签
symbol
标记,记号
within
在……内
definition
限定,界定
deliberately
慎重,谨慎的
vague
模糊,不确定
PS: deliberately vague  (有意含糊的)
content
内容
serve
提供
structure
组织,构造
statement
声明
grab
surrounded
包围
variable
变量
renders 
呈递
context
上下文
hole
坑,洞

======================== 

 

Using the template system

class django.template.Template

Using the template system in Python is a two-step process:

  • First, you compile the raw template code into a Template object.
  • Then, you call the render() method of the Template object with a given context.

Compiling a string

The easiest way to create a Template object is by instantiating it directly. The class lives at django.template.Template. The constructor takes one argument -- the raw template code:

>>> from django.template import Template
>>> t = Template("My name is {{ my_name }}.")
>>> print t
<django.template.Template instance>

Behind the scenes

The system only parses your raw template code once -- when you create the Template object. From then on, it's stored internally as a "node" structure for performance.

Even the parsing itself is quite fast. Most of the parsing happens via a single call to a single, short, regular expression.

使用模板系统

 

class django.template.Template  

在python中使用模板系统需要进行一下两个步骤

首先,把原始模板代码编辑进Template对象

然后,根据你的上下文调用Template对象的render()方法

编辑字符串

   最简单的方法就是直接初始化一个Template对象。这个类在django.template.Template中,构造器需要一个实参——原始模板代码。

====示例=====

 幕后:

    当你创建Template对象的时候,系统只会解析你的原始模板代码一次。从那时起,为了性能,它被存储为 "node" 结构

    即使这个自身解析是非常快速的 。多数的解析发生在一个独立的调用一个独立的,短小的正则表达式。(这非常不了解,求解)


Rendering a context

render(context)

Once you have a compiled Template object, you can render a context -- or multiple contexts -- with it. The Context class lives atdjango.template.Context, and the constructor takes two (optional) arguments:

  • A dictionary mapping variable names to variable values.
  • The name of the current application. This application name is used to help resolve namespaced URLs. If you're not using namespaced URLs, you can ignore this argument.

Call the Template object's render() method with the context to "fill" the template:

>>> from django.template import Context, Template
>>> t = Template("My name is {{ my_name }}.")

>>> c = Context({"my_name": "Adrian"})
>>> t.render(c)
"My name is Adrian."

>>> c = Context({"my_name": "Dolores"})
>>> t.render(c)
"My name is Dolores."

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore or a dot.

呈递一个上下文。

render(context) 

当你要编译一个Template对象,你可以为它呈递一个上下文-或多个上下文 。这个Context对象在django.template.Context,构造器需要两个(选项)实参:

 

    一个映射了变量名和变量值的字典。

    当前应用程序的名字。这个应用程序的名字用来帮助resolve namespaced URLs.如果你不使用namespaced URLs,你可以忽略这个参数。

根据上下文调用Template对象的render()方法来“填充”此模板:

=======实例========

变量命名须由字母(a-z), 数字0-9,下划线或.号组成

 

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup. Example: foo["bar"]
  • Attribute lookup. Example: foo.bar
  • List-index lookup. Example: foo[bar]

The template system uses the first lookup type that works. It's short-circuit logic. Here are a few examples:

>>> from django.template import Context, Template
>>> t = Template("My name is {{ person.first_name }}.")
>>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
>>> t.render(Context(d))
"My name is Joe."

>>> class PersonClass: pass
>>> p = PersonClass()
>>> p.first_name = "Ron"
>>> p.last_name = "Nasty"
>>> t.render(Context({"person": p}))
"My name is Ron."

>>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
>>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
>>> t.render(c)
"The first stooge in the list is Larry."
 .号在模板的呈递中有特殊的意思。.号在变量中象征着 寻找。特别地,当模板系统在变量名中遭遇.号时,模板系统会尝试顺从以下秩序寻找。

 

    字典查找,如foo["bar"] 

    属性查找,如foo.bar

    List索引查找,如foo[bar] 

模板系统使用第一个匹配的查找类型,这是短路逻辑。这里有一些事例。

====例=== 

 

If any part of the variable is callable, the template system will try calling it. Example:

>>> class PersonClass2:
...     def name(self):
...         return "Samantha"
>>> t = Template("My name is {{ person.name }}.")
>>> t.render(Context({"person": PersonClass2}))
"My name is Samantha."
Changed in Django 1.3: Previously, only variables that originated with an attribute lookup would be called by the template system. This change was made for consistency across lookup types.

如果某些变量是可以调用的,模板系统将会尝试调用它,如:

=====例子========

django 1.3的变更: 在以前,模板系统只能调用变量的原始属性。这个改变有利于查找的一致性。

Callable variables are slightly more complex than variables which only require straight lookups. Here are some things to keep in mind:

  • If the variable raises an exception when called, the exception will be propagated, unless the exception has an attributesilent_variable_failure whose value is True. If the exception does have a silent_variable_failure attribute whose value isTrue, the variable will render as an empty string. Example:

    >>> t = Template("My name is {{ person.first_name }}.")
    >>> class PersonClass3:
    ...     def first_name(self):
    ...         raise AssertionError("foo")
    >>> p = PersonClass3()
    >>> t.render(Context({"person": p}))
    Traceback (most recent call last):
    ...
    AssertionError: foo
    
    >>> class SilentAssertionError(Exception):
    ...     silent_variable_failure = True
    >>> class PersonClass4:
    ...     def first_name(self):
    ...         raise SilentAssertionError
    >>> p = PersonClass4()
    >>> t.render(Context({"person": p}))
    "My name is ."

 调用变量比只在变量上直接寻找略有些复杂。这有一些东西要铭记于心:

      如果变量被调用时提出一个exception,这个exception将会扩散,除非这个exception有silent_variable_failure属性,且值为True.如果exception有silent_variable_failure属性且值为True,那么变量将会呈递一个空string.如:

==============例子==========

 

==============

 单词:

Compiling 
汇集,编辑,编制
raw 
原始
Behind the scenes
幕后
parses 
转换
stored internally
内部存储
performance
性能
via
经过
context
上下文
resolve 
解决
ignore
忽略
consist of 
由……组成
digit
数字
underscore
下划线
signifies
象征
Specifically
特别地
encounters 
遭遇
Previously
以前 
originated 
引起
made for 
有利于
consistency across
之间的一致性
slightly
略,稍
complex
复杂
straight
直接的
keep in mind
铭记于心
raises
提升,提出
propagated
扩散
unless
除非
 

 

=========== 

  • Note that django.core.exceptions.ObjectDoesNotExist, which is the base class for all Django database API DoesNotExistexceptions, has silent_variable_failure = True. So if you're using Django templates with Django model objects, any DoesNotExistexception will fail silently.

  • A variable can only be called if it has no required arguments. Otherwise, the system will return an empty string.

  • Obviously, there can be side effects when calling some variables, and it'd be either foolish or a security hole to allow the template system to access them.

 django.core.exceptions.ObjectDoesNotExist 是所有Django数据库APT DoesNotExist异常的基类,有silent_variable_failure=True.所以,如果你使用Django模板的Django模型对象,所有的DoesNotExist异常都会不会有提示。

 

 变量只能进行无参数的调用, 否则,系统将会返回空字符串。

 显然, 当你调用多个变量,以及愚蠢或使用模板系统的安全漏洞来访问时,将会引起意外结果。

 

  • A good example is the delete() method on each Django model object. The template system shouldn't be allowed to do something like this:

    I will now delete this valuable data. {{ data.delete }}

    To prevent this, set an alters_data attribute on the callable variable. The template system won't call a variable if it has alters_data=Trueset. The dynamically-generated delete() and save() methods on Django model objects get alters_data=True automatically. Example:

    def sensitive_function(self):
        self.database_record.delete()
    sensitive_function.alters_data = True
    

    一个好的例子就是Django model 对象的delete()方法 ,末班系统不会允许一些情况如下:

     =====例子=======

    为了防止这情况,设置一个alters_data属性来调用变量。如果他的alters_data=True被设置,模板系统不会调用这个变量。Django模板对象动态生成的delete()和save()方法会自动获取alters_data=True。例如:

     =====例子=======

    How invalid variables are handled

    Generally, if a variable doesn't exist, the template system inserts the value of the TEMPLATE_STRING_IF_INVALID setting, which is set to '' (the empty string) by default.

    Filters that are applied to an invalid variable will only be applied if TEMPLATE_STRING_IF_INVALID is set to '' (the empty string). IfTEMPLATE_STRING_IF_INVALID is set to any other value, variable filters will be ignored.

    This behavior is slightly different for the iffor and regroup template tags. If an invalid variable is provided to one of these template tags, the variable will be interpreted as None. Filters are always applied to invalid variables within these template tags.

    If TEMPLATE_STRING_IF_INVALID contains a '%s', the format marker will be replaced with the name of the invalid variable.

    For debug purposes only!

    While TEMPLATE_STRING_IF_INVALID can be a useful debugging tool, it is a bad idea to turn it on as a 'development default'.

    Many templates, including those in the Admin site, rely upon the silence of the template system when a non-existent variable is encountered. If you assign a value other than '' to TEMPLATE_STRING_IF_INVALID, you will experience rendering problems with these templates and sites.

    Generally, TEMPLATE_STRING_IF_INVALID should only be enabled in order to debug a specific template problem, then cleared once debugging is complete. 

    如何处理无效变量

     一般来说,如果一个变量不存在,末班系统会插入一个来自TEMPLATE_STRING_IF_INVALID设置,并默认设置为''空字符串。

      过滤器只是使用于那些设置了TEMPLATE_STRING_IF_INVALID为''空字符串的那些 变量。如果TEMPLATE_STRING_IF_INVALID 设置为其他值,则过滤器将会被忽略。

       这个行为对于if,for和regroup模板标记略有不同。如果一个不正常的变量被提供一个这样的模板标记,这个变量将会被翻译为None,在这个模板标记中,过滤器将会始终适用于这个变量。

      如果TEMPLATE_STRING_IF_INVALID  包含一个'%s',则格式化标记将会被替换成一个无效变量的名字。

                   只供debug之用!

                   当TEMPLATE_STRING_IF_INVALID 在debugging工具中有效时,切换到‘development default'是一个坏决定。

                   在Admin站,很多模板都包括这个, 当模板系统遇到一个不存在的变量时将会静默。如果你指定一个''值意外的值给TEMPLATE_STRING_IF_INVALID,在这个模板和网站中,你将会面临呈递问题。

      一般来说,TEMPLATE_STRING_IF_INVALID 将只能被允许安排在debug一个特殊的模板问题,并且在debugging完成时会第一时间被清理。

     

     

    Playing with Context objects

    class django.template.Context

    Most of the time, you'll instantiate Context objects by passing in a fully-populated dictionary to Context(). But you can add and delete items from a Context object once it's been instantiated, too, using standard dictionary syntax:

    >>> c = Context({"foo": "bar"})
    >>> c['foo']
    'bar'
    >>> del c['foo']
    >>> c['foo']
    ''
    >>> c['newvariable'] = 'hello'
    >>> c['newvariable']
    'hello'

     

     

     与上下文对象一起嬉戏!

     class django.template.Context

     更多的时候,你为传入一个填充好的字典给Context()时需要初始化Context对象 。不过在Context对象被初始化的时候你也可以使用标准的字典语法来添加和删除项:

    ===例子====

     

    pop()
    push()
    exception django.template.ContextPopException

    Context object is a stack. That is, you can push() and pop() it. If you pop() too much, it'll raise django.template.ContextPopException:

    >>> c = Context()
    >>> c['foo'] = 'first level'
    >>> c.push()
    >>> c['foo'] = 'second level'
    >>> c['foo']
    'second level'
    >>> c.pop()
    >>> c['foo']
    'first level'
    >>> c['foo'] = 'overwritten'
    >>> c['foo']
    'overwritten'
    >>> c.pop()
    Traceback (most recent call last):
    ...
    django.template.ContextPopException
     

     pop()

    push()

    exception django.template.ContextPopException

    一个上下文对象是一个堆,因此,你可以push()和pop()它,如果你过度pop(),它将会提出 django.template.ContextPopException:

    =====例子==== 

 

update(other_dict)

In addition to push() and pop(), the Context object also defines an update() method. This works like push() but takes a dictionary as an argument and pushes that dictionary onto the stack instead of an empty one.

>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.update({'foo': 'updated'})
{'foo': 'updated'}
>>> c['foo']
'updated'
>>> c.pop()
{'foo': 'updated'}
>>> c['foo']
'first level'

Using a Context as a stack comes in handy in some custom template tags, as you'll see below.

 

   update(oter_dict)

    在追加push()和pop()时,Context对象也会定义一个update()方法。这个方法如push()一样工作,但是它会将一个字典作为参数,并且将它推入到堆中替换一个空的。

   在模板标记中提交使用一个context就像是一个堆,如你之前所见的一样。

 

Subclassing Context: RequestContext

class django.template.RequestContext

Django comes with a special Context class, django.template.RequestContext, that acts slightly differently than the normaldjango.template.Context. The first difference is that it takes an HttpRequest as its first argument. For example:

c = RequestContext(request, {
    'foo': 'bar',
})
 

 

 子类上下文:RequestContext

  class django.template.RequestContext

Django 提供一个特殊的Context 类——django.template.RequestContext,他的行为与普通的django.templtate.Context略有不同。第一点就是他使用HttpRequest作为第一参数,如:

 

The second difference is that it automatically populates the context with a few variables, according to yourTEMPLATE_CONTEXT_PROCESSORS setting.

The TEMPLATE_CONTEXT_PROCESSORS setting is a tuple of callables -- called context processors -- that take a request object as their argument and return a dictionary of items to be merged into the context. By default, TEMPLATE_CONTEXT_PROCESSORS is set to:

("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")
New in Django 1.2: In addition to these, RequestContext always uses django.core.context_processors.csrf. This is a security related context processor required by the admin and other contrib apps, and, in case of accidental misconfiguration, it is deliberately hardcoded in and cannot be turned off by the TEMPLATE_CONTEXT_PROCESSORS setting.
New in Django 1.2: The 'messages' context processor was added. For more information, see the messages documentation.
Changed in Django 1.2: The auth context processor was moved in this release from its old locationdjango.core.context_processors.auth to django.contrib.auth.context_processors.auth.

 

  第二点就是根据你的TEMPLATE_CONTEXT_PROCESSORS设置使一些变量自动构成上下文。

  TEMPLATE_CONTEXT_PROCESSORS设置被调用时是一个名为context processors 的元组类型,它使用request对象作为它的参数并且返回一个已经合并项的字典。TEMPLATE_CONTEXT_PROCESSORS的默认设置如下:

 ===例子==========

  Django 1.2新特性:除了上述这些,RequestContext总是使用django.core.context_processors.csrf。这是一个来自admin或者其他开源应用。。。与安全相关的上下文处理请求 ,它谨慎的使用一个固定变来使得不能更改TEMPLATE_CONTEXT_PROCESSORS设置。

  Django 1.2新特性:'messages'上下文处理被添加了。更多信息请查看。。。

  django1.2变更:验证上下文处理从django.core.context_processors.auth移动到django.contrib.auth.context_processors.auth。

 

 

Each processor is applied in order. That means, if one processor adds a variable to the context and a second processor adds a variable with the same name, the second will override the first. The default processors are explained below.

When context processors are applied

When you use RequestContext, the variables you supply directly are added first, followed any variables supplied by context processors. This means that a context processor may overwrite a variable you've supplied, so take care to avoid variable names which overlap with those supplied by your context processors.

Also, you can give RequestContext a list of additional processors, using the optional, third positional argument, processors. In this example, the RequestContext instance gets a ip_address variable:

def ip_address_processor(request):
    return {'ip_address': request.META['REMOTE_ADDR']}

def some_view(request):
    # ...
    c = RequestContext(request, {
        'foo': 'bar',
    }, [ip_address_processor])
    return HttpResponse(t.render(c))

Note

If you're using Django's render_to_response() shortcut to populate a template with the contents of a dictionary, your template will be passed a Context instance by default (not a RequestContext). To use a RequestContext in your template rendering, pass an optional third argument to render_to_response(): a RequestContext instance. Your code might look like this:

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))

Here's what each of the default processors does:

 

 

   這種處理是合理的。这代表如果一个处理器添加一个比昂两到上下文并且第二个处理器添加一个同名的变量,第二个则会覆盖第一个,默认的处理将向下解析 

            当上下文处理器被应用时:

            当你使用RequestContext,你提交的字典变量将会被第一时间添加,接着一些变量将会被处理器提供。这表明上下文处理器会重写你提供的变量。所以请小心避免部分重复的变量名在你的上下文处理器中被提供。

同样,你可以给RequestContext一个额外的处理器列表,使用其他选项,三个位置参数,processors,如下所例,RequestContext 在初始化时候获得ip_address变量:

     笔记:

    如果使用django的render_to_response() 快捷方式和一个有内容的字典去填充模板,你的模板将会默认地被一个Context对象初始化而不是RequestContext。在呈递模板时要使用RequestContext的话,必选传入一个任意的第三参数给render_to_response():一个初始化的RequestContext对象,你的实现代码将会看起来是这样子:

    ===代码=====

 

 下面是每一个默认的处理器的: 

 

django.contrib.auth.context_processors.auth

If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain these three variables:

  • user -- An auth.User instance representing the currently logged-in user (or an AnonymousUser instance, if the client isn't logged in).
  • messages -- A list of messages (as strings) that have been set via the messages framework.
  • perms -- An instance of django.contrib.auth.context_processors.PermWrapper, representing the permissions that the currently logged-in user has.
Changed in Django 1.2: This context processor was moved in this release from django.core.context_processors.auth to its current location.
Changed in Django 1.2: Prior to version 1.2, the messages variable was a lazy accessor for user.get_and_delete_messages(). It has been changed to include any messages added via the messages framework.
Changed in Django 1.3: Prior to version 1.3, PermWrapper was located in django.contrib.auth.context_processors.

 

django.contrib.auth.context_processors.auth

如果 TEMPLACT_CONTEXT_PROCESSORS 包含有处理,所有的RequestContext将会包含如下三个变量:

   user --代表一个auth.User实例 ——当前已经登录了的(或者是一个AnonymousUser,如果未登录的话)

   messages --一个经过messages framework设置了的消息列表(string) 

   perms -- 一个django.contrib.auth.context_processors.PermWrapper实例,代表当前登录用户所有的权限。

 

django1.2变更:这个上下文处理器已经移动到析出的form django.core.context_processors.auth。

django1.2变更: 在1.2版本前,messages变量是user.get_and_delete_messages()的懒惰访问。这将改变所有包含有一些经由messages framework添加过的messages

django1.3变更: 在1.3版本前,PermWrapper已经在django.contrib.auth.coutext_processors

 

posted @ 2011-09-27 14:08  snowlueng  阅读(1219)  评论(0编辑  收藏  举报