Differences between revisions 4 and 14 (spanning 10 versions)
Revision 4 as of 2007-06-15 06:00:03
Size: 9480
Editor: HuangYi
Comment:
Revision 14 as of 2009-12-25 07:09:16
Size: 9465
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 4: Line 4:
:进度: 草稿;HuangYi;完成度0%; :进度: 草稿;HuangYi & NeilChen;完成度0%;
Line 13: Line 13:
The def is the single tag used to demarcate any block of text and/or code. It exists within generated Python as a callable function. :: def 是一个 tag ,它包含一块文本和/或代码。而在编译后的 python 代码中,它就是一个 python 函数。 ::
Line 19: Line 19:
They are normally called as expressions. :: 通常他们就像执行表达式一样被调用。::
Line 23: Line 23:
If the ``<%def>`` is not nested inside of another ``<%def>``, its known as a top level def and can be accessed anywhere in the template, including above where it was defined.

All defs, top level or not, have access to the current contextual namespace in exactly the same way their containing template does. Suppose the template below is executed with the variables username and accountdata inside the context: ::
如果 ``<%def>`` 没有嵌套在另一个 ``<%def>`` 里面,它就是一个顶层 def,在模板的任何位置都可以访问到它,甚至在定义它之前的地方也行。

所有 defs ,不管是否顶层 def ,都能够和包含他们的模板以同样的方式访问当前名字空间。假设下面这个模板的名字空间中有两个变量 ``username`` 和 ``accountdata`` :::
Line 39: Line 39:
The ``username`` and ``accountdata`` variables are present within the main template body as well as the body of the ``account()`` def.

Since defs are just Python functions, you can define and pass arguments to them as well: ::
``username`` 和 ``accountdata`` 两个变量将会显示在主模板的 body 中,同样也会显示在 ``account()`` def 的 body 中。

既然 defs 不过就是 python 函数,你自然也能够定义和传递参数了。::
Line 49: Line 49:
When you declare an argument signature for your def, they are required following normal Python conventions (i.e., all arguments are required except keyword arguments with a default value). This is in contrast to using context-level variables, which evaluate to UNDEFINED if you reference a name that does not exist.

Calling defs from Other Files
-----------------------------

Top level ``<%defs>`` are exported by your template's module, and can be called from the outside; including from other templates, as well as normal Python code. Calling a ``<%def>`` from another template is something like using an ``<%include>`` - except you are calling a specific function within the template, not the whole template.

The remote ``<%def>`` call is also a little bit like calling functions from other modules in Python. There is an "import" step to pull the names from another template into your own template; then the function or functions are available.

To import another template, use the ``<%namespace>`` tag: ::
当你为 def 定义参数时,他们需要遵从 Python 的规定(比如调用时必须提供关键字参数以外的所有参数)。这和名字空间变量的使用方式不同,如果访问一个名字空间中不存在的变量,会返回一个 UNDEFINED 而不是出错。

从其他文件调用 defs
-------------------------

顶层的 ``<%defs>`` 被编译到模板对应的模块中,并且可以被从外部调用;包括从其他模板,或是普通的 Python 代码来调用。从其他模板中调用 ``<%def>`` 有点像使用 ``<%include>`` —— 差别在于,你是在调用模板中的一个函数,而不是整个模板。

远程的 ``<%def>`` 调用也有点类似于 Python 中调用另一个模块中的函数的情形。需要有一个“导入”的步骤,以便从其他模板中萃取出名称,添加到你自己的模板中;然后这些名称的函数才可以被调用。

要导入另一个模板,使用 ``<%namespace>`` 标签:::
Line 62: Line 62:
The above tag adds a local variable "mystuff" to the current scope.

Then, just call the defs off of mystuff: ::
上面的标签添加了一个局部变量 "mystuff" 到当前范围中。

然后,只要调用 mystuff 中的函数即可:::
Line 68: Line 68:
The ``<%namespace>`` tag also supports some of the other semantics of Python's import statement, including pulling names into the local variable space, or using ``*`` to represent all names, using the import attribute: ``<%namespace>`` 标签还支持类似 Python import 语句的一些其他的语义,包括将名称提取到局部变量空间中,或使用 ``*`` 来代表所有名称,使用 import 属性:::
Line 72: Line 72:
This is just a quick intro to the concept of a namespace, which is a central Mako concept that has its own chapter in these docs. For more detail and examples, see [:/Namespaces: Namespaces]. 这里只是对名称空间的概念做了一个简单的介绍,名称空间是 Mako 的一个核心概念,在文档中有独立的章节介绍。更多的细节和例子,见 [:/Namespaces: Namespaces]。
Line 77: Line 77:
The def model follows regular Python rules for closures. Declaring ``<%def>`` inside another ``<%def>`` declares it within the parent's **enclosing scope**::: The def model follows regular Python rules for closures. Declaring ``<%def>`` inside another ``<%def>`` declares it within the parent's **enclosing scope**: ::
Rendering of reStructured text is not possible, please install Docutils.
:进度: 草稿;HuangYi & NeilChen;完成度0%;
:原文: http://www.makotemplates.org/docs/defs.html;

.. contents::
  :depth: 3

Defs
====

def 是一个 tag ,它包含一块文本和/或代码。而在编译后的 python 代码中,它就是一个 python 函数。 ::

    <%def name="hello()">
        hello world
    </%def>

通常他们就像执行表达式一样被调用。::

    the def:  ${hello()}

如果 ``<%def>`` 没有嵌套在另一个 ``<%def>`` 里面,它就是一个顶层 def,在模板的任何位置都可以访问到它,甚至在定义它之前的地方也行。

所有 defs ,不管是否顶层 def ,都能够和包含他们的模板以同样的方式访问当前名字空间。假设下面这个模板的名字空间中有两个变量 ``username`` 和 ``accountdata`` :::

    Hello there ${username}, how are ya.  Lets see what your account says:

    ${account()}

    <%def name="account()">
        Account for ${username}:<br/>

        % for row in accountdata:
            Value: ${row}<br/>
        % endfor
    </%def>

``username`` 和 ``accountdata`` 两个变量将会显示在主模板的 body 中,同样也会显示在 ``account()`` def 的 body 中。

既然 defs 不过就是 python 函数,你自然也能够定义和传递参数了。::

    ${account(accountname='john')}

    <%def name="account(accountname, type='regular')">
        account name: ${accountname}, type ${type}
    </%def>

当你为 def 定义参数时,他们需要遵从 Python 的规定(比如调用时必须提供关键字参数以外的所有参数)。这和名字空间变量的使用方式不同,如果访问一个名字空间中不存在的变量,会返回一个 UNDEFINED 而不是出错。

从其他文件调用 defs
-------------------------

顶层的 ``<%defs>`` 被编译到模板对应的模块中,并且可以被从外部调用;包括从其他模板,或是普通的 Python 代码来调用。从其他模板中调用 ``<%def>`` 有点像使用 ``<%include>`` —— 差别在于,你是在调用模板中的一个函数,而不是整个模板。

远程的 ``<%def>`` 调用也有点类似于 Python 中调用另一个模块中的函数的情形。需要有一个“导入”的步骤,以便从其他模板中萃取出名称,添加到你自己的模板中;然后这些名称的函数才可以被调用。

要导入另一个模板,使用 ``<%namespace>`` 标签:::

    <%namespace name="mystuff" file="mystuff.html"/>

上面的标签添加了一个局部变量 "mystuff" 到当前范围中。

然后,只要调用 mystuff 中的函数即可:::

    ${mystuff.somedef(x=5,y=7)}

``<%namespace>`` 标签还支持类似 Python import 语句的一些其他的语义,包括将名称提取到局部变量空间中,或使用 ``*`` 来代表所有名称,使用 import 属性:::

    <%namespace file="mystuff.html" import="foo, bar"/>

这里只是对名称空间的概念做了一个简单的介绍,名称空间是 Mako 的一个核心概念,在文档中有独立的章节介绍。更多的细节和例子,见 [:/Namespaces: Namespaces]。

Defs within Defs 
----------------

The def model follows regular Python rules for closures. Declaring ``<%def>`` inside another ``<%def>`` declares it within the parent's **enclosing scope**: ::

    <%def name="mydef()">
        <%def name="subdef()">
            a sub def
        </%def>

        im the def, and the subcomopnent is ${subdef()}
    </%def>

Just like Python, names that exist outside the inner ``<%def>`` exist inside it as well: ::

    <%
        x = 12
    %>
    <%def name="outer()">
        <%
            y = 15
        %>
        <%def name="inner()">
            inner, x is ${x}, y is ${y}
        </%def>

        outer, x is ${x}, y is ${y}
    </%def>

Assigning to a name inside of a def declares that name as local to the scope of that def (again, like Python itself). This means the following code will raise an error: ::

    <%
        x = 10
    %>
    <%def name="somedef()">
        # error !
        somedef, x is ${x}  
        <%
            x = 27  
        %>
    </%def>

...because the assignment to ``x`` declares ``x`` as local to the scope of ``somedef``, rendering the "outer" version unreachable in the expression that tries to render it. 

Calling a def with embedded content and/or other defs 
-----------------------------------------------------

A flip-side to def within def is a def call with content. This is where you call a def, and at the same time declare a block of content (or multiple blocks) that can be used by the def being called. The main point of such a call is to create custom, nestable tags, just like any other template language's custom-tag creation system - where the external tag controls the execution of the nested tags and can communicate state to them. Only with Mako, you don't have to use any external Python modules, you can define arbitrarily nestable tags right in your templates. 

To achieve this, the target def is invoked using the ``<%call>`` tag instead of the normal ``${}`` syntax. The target def then gets a variable caller placed in its context which contains a **namespace** containing the body and other defs defined within the ``<%call>`` tag. The body itself is referenced by the method ``body()``: ::

    <%def name="buildtable()">
        <table>
            <tr><td>
                ${caller.body()}
            </td></tr>
        </table>
    </%def>

    <%call expr="buildtable">
        I am the table body.
    </%call>

This produces the output (whitespace formatted): ::

    <table>
        <tr><td>
            I am the table body.
        </td></tr>
    </table>

The ``body()`` can be executed multiple times or not at all. This means you can use def-call-with-content to build iterators, conditionals, etc: ::

    <%def name="lister(count)">
        % for x in range(1,count):
            ${caller.body()}
        % endfor
    </%def>

    <%call expr="lister(3)">
        hi
    </%call>

Produces: ::

    hi
    hi
    hi

A custom "conditional" tag: ::

    <%def name="conditional(expr)">
        % if expr:
            ${caller.body()}
        % endif
    </%def>

    <%call expr="conditional(4==4)">
        im the result
    </%call>

Produces: ::

    im the result

But that's not all. The ``body()`` function also can handle arguments, which will augment the local namespace of the body callable: ::

    <%def name="layoutdata(somedata)">
        <table>
        % for item in somedata:
            <tr>
            % for col in item:
                <td>${caller.body(col=col)}</td>\
            % endfor
            </tr>
        % endfor
        </table>
    </%def>

    <%call expr="layoutdata([[1,2,3],[4,5,6],[7,8,9]])" args="col">
        Body data: ${col}
    </%call>

Produces (whitespace formatted): ::

    <table>
        <tr>
            <td>Body data: 1</td><td>Body data: 2</td><td>Body data: 3</td>
            <td>Body data: 4</td><td>Body data: 5</td><td>Body data: 6</td>
            <td>Body data: 7</td><td>Body data: 8</td><td>Body data: 9</td>
        </tr>
    </table>

You don't have to stick to calling just the ``body()`` function. The caller can define any number of callables, allowing the ``<%call>`` tag to produce whole layouts: ::

    <%def name="layout()">
        # a layout def
        <div class="mainlayout">
            <div class="header">
                ${caller.header()}
            </div>
            <div class="sidebar">
                ${caller.sidebar()}
            </div>
            <div class="content">
                ${caller.body()}
            </div>
        </div>
    </%def>

    # calls the layout def
    <%call expr="layout">
        <%def name="header()">
            I am the header
        </%def>
        <%def name="sidebar()">
            <ul>
                <li>sidebar 1</li>
                <li>sidebar 2</li>
            </ul>
        </%def>

            this is the body
    </%call>

The above layout would produce (whitespace formatted): ::

    <div class="mainlayout">
        <div class="header">
            I am the header
        </div>
        <div class="sidebar">
            <ul>
                <li>sidebar 1</li>
                <li>sidebar 2</li>
            </ul>
        </div>
        <div class="content">
            this is the body
        </div>
    </div>

The number of things you can do with ``<%call>`` is enormous. You can create form widget libraries, such as an enclosing ``<FORM>`` tag and nested HTML input elements, or portable wrapping schemes using ``<div>`` or other elements. You can create tags that interpret rows of data, such as from a database, providing the individual columns of each row to a ``body()`` callable which lays out the row any way it wants. Basically anything you'd do with a "custom tag" or tag library in some other system, Mako provides via ``<%def>``s or even plain Python callables which are called via ``<%call>``. 



.. macro:: [[PageComment2(nosmiley=1, notify=1)]]


.. macro:: -- HuangYi [[[DateTime(2007-06-15T05:37:02Z)]]]

MaKo/Defs (last edited 2009-12-25 07:09:16 by localhost)