summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2010-11-12 16:05:47 -0500
committerMike Bayer <mike_mp@zzzcomputing.com>2010-11-12 16:05:47 -0500
commit4ce916525fd94116e696f4d8cde19333e9ed946c (patch)
tree1ac15a03c68d6b401278c4b4d601835cf5fa8b7a
parentd0f607201ebbbeecc60880455aacb690906563bd (diff)
downloadmako-4ce916525fd94116e696f4d8cde19333e9ed946c.tar.gz
moving along
-rw-r--r--doc/build/defs.rst435
-rw-r--r--doc/build/syntax.rst415
-rw-r--r--doc/build/templates/site_base.mako5
-rw-r--r--doc/build/unicode.rst4
-rw-r--r--doc/build/usage.rst156
-rw-r--r--mako/template.py2
6 files changed, 938 insertions, 79 deletions
diff --git a/doc/build/defs.rst b/doc/build/defs.rst
index 8b13789..1e3abb6 100644
--- a/doc/build/defs.rst
+++ b/doc/build/defs.rst
@@ -1 +1,436 @@
+.. _defs_toplevel:
+
+====
+Defs
+====
+
+``<%def>`` is the single tag used to demarcate any block of text
+and/or code. It exists within generated Python as a callable
+function:
+
+.. sourcecode:: mako
+
+ <%def name="hello()">
+ hello world
+ </%def>
+
+They are normally called as expressions:
+
+.. sourcecode:: mako
+
+ the def: ${hello()}
+
+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:
+
+.. sourcecode:: mako
+
+ 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>
+
+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:
+
+.. sourcecode:: mako
+
+ ${account(accountname='john')}
+
+ <%def name="account(accountname, type='regular')">
+ account name: ${accountname}, type ${type}
+ </%def>
+
+When you declare an argument signature for your def, they are
+required to follow 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:
+
+.. sourcecode:: mako
+
+ <%namespace name="mystuff" file="mystuff.html"/>
+
+The above tag adds a local variable "mystuff" to the current
+scope.
+
+Then, just call the defs off of ``mystuff``:
+
+.. sourcecode:: mako
+
+ ${mystuff.somedef(x=5,y=7)}
+
+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:
+
+.. sourcecode:: mako
+
+ <%namespace file="mystuff.html" import="foo, bar"/>
+
+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
+:ref:`namespaces_toplevel`.
+
+Calling defs programmatically
+==============================
+
+You can call def's programmatically from any :class:`.Template` object
+using the :meth:`~.Template.get_def()` method, which returns a :class:`.DefTemplate`
+object. This is a :class:`.Template` subclass which the parent
+:class:`.Template` creates, and is usable like any other template:
+
+.. sourcecode:: python
+
+ from mako.template import Template
+
+ template = Template("""
+ <%def name="hi(name)">
+ hi ${name}!
+ </%def>
+
+ <%def name="bye(name)">
+ bye ${name}!
+ </%def>
+ """)
+
+ print template.get_def("hi").render(name="ed")
+ print template.get_def("bye").render(name="ed")
+
+
+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**:
+
+.. sourcecode:: mako
+
+ <%def name="mydef()">
+ <%def name="subdef()">
+ a sub def
+ </%def>
+
+ im the def, and the subcomponent is ${subdef()}
+ </%def>
+
+Just like Python, names that exist outside the inner ``<%def>``
+exist inside it as well:
+
+.. sourcecode:: mako
+
+ <%
+ 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:
+
+.. sourcecode:: mako
+
+ <%
+ 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.
+
+.. _defs_with_content:
+
+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 form
+``<%namepacename:defname>`` instead of the normal ``${}``
+syntax. This syntax, introduced in Mako 0.2.3, is functionally
+equivalent another tag known as ``call``, which takes the form
+``<%call expr='namespacename.defname(args)'>``. While ``%call``
+is available in all versions of Mako, the newer style is
+probably more familiar looking. The ``namespace`` portion of the
+call is the name of the **namespace** in which the def is
+defined - in the most simple cases, this can be ``local`` or
+``self`` to reference the current template's namespace (the
+difference between ``local`` and ``self`` is one of inheritance
+- see :ref:`namespaces_builtin` for details).
+
+When the target def is invoked, a variable ``caller`` is placed
+in its context which contains another namespace containing the
+body and other defs defined by the caller. The body itself is
+referenced by the method ``body()``. Below, we build a ``%def``
+that operates upon ``caller.body()`` to invoke the body of the
+custom tag:
+
+.. sourcecode:: mako
+
+ <%def name="buildtable()">
+ <table>
+ <tr><td>
+ ${caller.body()}
+ </td></tr>
+ </table>
+ </%def>
+
+ <%self:buildtable>
+ I am the table body.
+ </%self:buildtable>
+
+This produces the output (whitespace formatted):
+
+.. sourcecode:: html
+
+ <table>
+ <tr><td>
+ I am the table body.
+ </td></tr>
+ </table>
+
+Using the older ``%call`` syntax looks like:
+
+.. sourcecode:: mako
+
+ <%def name="buildtable()">
+ <table>
+ <tr><td>
+ ${caller.body()}
+ </td></tr>
+ </table>
+ </%def>
+
+ <%call expr="buildtable()">
+ I am the table body.
+ </%call>
+
+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:
+
+.. sourcecode:: mako
+
+ <%def name="lister(count)">
+ % for x in range(count):
+ ${caller.body()}
+ % endfor
+ </%def>
+
+ <%self:lister count="${3}">
+ hi
+ </%self:lister>
+
+Produces:
+
+.. sourcecode:: html
+
+ hi
+ hi
+ hi
+
+Notice above we pass ``3`` as a Python expression, so that it
+remains as an integer.
+
+A custom "conditional" tag:
+
+.. sourcecode:: mako
+
+ <%def name="conditional(expression)">
+ % if expression:
+ ${caller.body()}
+ % endif
+ </%def>
+
+ <%self:conditional expression="${4==4}">
+ im the result
+ </%self:conditional>
+
+Produces:
+
+.. sourcecode:: html
+
+ 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. The caller must define the arguments which it expects
+to receive from its target def using the ``args`` attribute,
+which is a comma-separated list of argument names. Below, our
+``<%def>`` calls the ``body()`` of its caller, passing in an
+element of data from its argument:
+
+.. sourcecode:: mako
+
+ <%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>
+
+ <%self:layoutdata somedata="${[[1,2,3],[4,5,6],[7,8,9]]}" args="col">\
+ Body data: ${col}\
+ </%self:layoutdata>
+
+Produces:
+
+.. sourcecode:: html
+
+ <table>
+ <tr>
+ <td>Body data: 1</td>
+ <td>Body data: 2</td>
+ <td>Body data: 3</td>
+ </tr>
+ <tr>
+ <td>Body data: 4</td>
+ <td>Body data: 5</td>
+ <td>Body data: 6</td>
+ </tr>
+ <tr>
+ <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:
+
+.. sourcecode:: mako
+
+ <%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
+ <%self: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
+ </%self:layout>
+
+The above layout would produce:
+
+.. sourcecode:: html
+
+ <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>`` and/or the
+``<%namespacename:defname>`` calling syntax 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>`` tags and plain Python callables which are
+invoked via ``<%namespacename:defname>`` or ``<%call>``.
+
+
diff --git a/doc/build/syntax.rst b/doc/build/syntax.rst
index 8b13789..4207570 100644
--- a/doc/build/syntax.rst
+++ b/doc/build/syntax.rst
@@ -1 +1,416 @@
+.. _syntax_toplevel:
+
+======
+Syntax
+======
+
+A Mako template is parsed from a text stream containing any kind
+of content, XML, HTML, email text, etc. The template can further
+contain Mako-specific directives which represent variable and/or
+expression substitutions, control structures (i.e. conditionals
+and loops), server-side comments, full blocks of Python code, as
+well as various tags that offer additional functionality. All of
+these constructs compile into real Python code. This means that
+you can leverage the full power of Python in almost every aspect
+of a Mako template.
+
+Expression Substitution
+========================
+
+The simplest expression is just a variable substitution. The
+syntax for this is the ``${}`` construct, which is inspired by
+Perl, Genshi, JSP EL, and others:
+
+.. sourcecode:: mako
+
+ this is x: ${x}
+
+Above, the string representation of ``x`` is applied to the
+template's output stream. If you're wondering where ``x`` comes
+from, its usually from the ``Context`` supplied to the
+template's rendering function. If ``x`` was not supplied to the
+template and was not otherwise assigned locally, it evaluates to
+a special value ``UNDEFINED``. More on that later.
+
+The contents within the ``${}`` tag are evaluated by Python
+directly, so full expressions are OK:
+
+.. sourcecode:: mako
+
+ pythagorean theorem: ${pow(x,2) + pow(y,2)}
+
+The results of the expression are evaluated into a string result
+in all cases before being rendered to the output stream, such as
+the above example where the expression produces a numeric
+result.
+
+Expression Escaping
+===================
+
+
+Mako includes a number of built-in escaping mechanisms,
+including HTML, URI and XML escaping, as well as a "trim"
+function. These escapes can be added to an expression
+substituion using the ``|`` operator:
+
+.. sourcecode:: mako
+
+ ${"this is some text" | u}
+
+The above expression applies URL escaping to the expression, and
+produces ``this+is+some+text``. The ``u`` name indicates URL
+escaping, whereas ``h`` represents HTML escaping, ``x``
+represents XML escaping, and ``trim`` applies a trim function.
+
+Read more about built in filtering functions, including how to
+make your own filter functions, in :ref:`filtering_toplevel`.
+
+Control Structures
+==================
+
+A control structure refers to all those things that control the
+flow of a program - conditionals (i.e. if/else), loops (like
+while and for), as well as things like ``try/except``. In Mako,
+control structures are written using the ``%`` marker followed
+by a regular Python control expression, and are "closed" by
+using another ``%`` marker with the tag "``end<name>``", where
+"``<name>``" is the keyword of the expression:
+
+.. sourcecode:: mako
+
+ % if x==5:
+ this is some output
+ % endif
+
+The ``%`` can appear anywhere on the line as long as no text
+precedes it; indentation is not signficant. The full range of
+Python "colon" expressions are allowed here, including
+``if/elif/else``, ``while``, ``for``, and even ``def``, although
+Mako has a built-in tag for defs which is more full-featured.
+
+.. sourcecode:: mako
+
+ % for a in ['one', 'two', 'three', 'four', 'five']:
+ % if a[0] == 't':
+ its two or three
+ % elif a[0] == 'f':
+ four/five
+ % else:
+ one
+ %endif
+ % endfor
+
+The ``%`` sign can also be "escaped", if you actually want to
+emit a percent sign as the first non whitespace character on a
+line, by escaping it as in ``%%``:
+
+.. sourcecode:: mako
+
+ %% some text
+
+ %% some more text
+
+Comments
+========
+
+Comments come in two varieties. The single line comment uses
+``##`` as the first non-space characters on a line:
+
+.. sourcecode:: mako
+
+ ## this is a comment.
+ ...text ...
+
+A multiline version exists using ``<%doc> ...text... </%doc>``:
+
+.. sourcecode:: mako
+
+ <%doc>
+ these are comments
+ more comments
+ </%doc>
+
+Newline Filters
+================
+
+The backslash ("``\``") character, placed at the end of any
+line, will consume the newline character before continuing to
+the next line:
+
+.. sourcecode:: mako
+
+ here is a line that goes onto \
+ another line.
+
+The above text evaluates to::
+
+ here is a line that goes onto another line.
+
+Python Blocks
+=============
+
+Any arbitrary block of python can be dropped in using the ``<%
+%>`` tags:
+
+.. sourcecode:: mako
+
+ this is a template
+ <%
+ x = db.get_resource('foo')
+ y = [z.element for z in x if x.frobnizzle==5]
+ %>
+ % for elem in y:
+ element: ${elem}
+ % endfor
+
+Within ``<% %>``, you're writing a regular block of Python code.
+While the code can appear with an arbitrary level of preceding
+whitespace, it has to be consistently formatted with itself.
+Mako's compiler will adjust the block of Python to be consistent
+with the surrounding generated Python code.
+
+Module-level Blocks
+====================
+
+A variant on ``<% %>`` is the module-level code block, denoted
+by ``<%! %>``. Code within these tags is executed at the module
+level of the template, and not within the rendering function of
+the template. Therefore, this code does not have access to the
+template's context and is only executed when the template is
+loaded into memory (which can be only once per application, or
+more, depending on the runtime environment). Use the ``<%! %>``
+tags to declare your template's imports, as well as any
+pure-Python functions you might want to declare:
+
+.. sourcecode:: mako
+
+ <%!
+ import mylib
+ import re
+
+ def filter(text):
+ return re.sub(r'^@', '', text)
+ %>
+
+Any number of ``<%! %>`` blocks can be declared anywhere in a
+template; they will be rendered in the resulting module in the
+order that they appear.
+
+Tags
+====
+
+The rest of what Mako offers takes place in the form of tags.
+All tags use the same syntax, which is similar to an XML tag
+except that the first character of the tag name is a ``%``
+character. The tag is closed either by a contained slash
+character, or an explicit closing tag:
+
+.. sourcecode:: mako
+
+ <%include file="foo.txt"/>
+
+ <%def name="foo" buffered="True">
+ this is a def
+ </%def>
+
+All tags have a set of attributes which are defined for each
+tag. Some of these attributes are required. Also, many
+attributes support **evaluation**, meaning you can embed an
+expression (using ``${}``) inside the attribute text:
+
+.. sourcecode:: mako
+
+ <%include file="/foo/bar/${myfile}.txt"/>
+
+Whether or not an attribute accepts runtime evaluation depends
+on the type of tag and how that tag is compiled into the
+template. The best way to find out if you can stick an
+expression in is to try it ! The lexer will tell you if its not
+valid.
+
+Heres a quick summary of all the tags:
+
+<%page>
+-------
+
+This tag defines general characteristics of the template,
+including caching arguments, and optional lists of arguments
+which the template expects when invoked.
+
+.. sourcecode:: mako
+
+ <%page args="x, y, z='default'"/>
+
+Or a page tag that defines caching characteristics:
+
+.. sourcecode:: mako
+
+ <%page cached="True" cache_type="memory"/>
+
+Currently, only one ``<%page>`` tag gets used per template, the
+rest get ignored. While this will be improved in a future
+release, for now make sure you have only one ``<%page>`` tag
+defined in your template, else you may not get the results you
+want. The details of what ``<%page>`` is used for are described
+further in :ref:`namespaces_body` as well as :ref:`caching_toplevel`.
+
+<%include>
+-----------
+
+A tag that is familiar from other template languages, %include
+is a regular joe that just accepts a file argument and calls in
+the rendered result of that file:
+
+.. sourcecode:: mako
+
+ <%include file="header.html"/>
+
+ hello world
+
+ <%include file="footer.html"/>
+
+Include also accepts arguments which are available as ``<%page>`` arguments in the receiving template:
+
+.. sourcecode:: mako
+
+ <%include file="toolbar.html" args="current_section='members', username='ed'"/>
+
+<%def>
+------
+
+The ``%def`` tag defines a Python function which contains a set
+of content, that can be called at some other point in the
+template. The basic idea is simple:
+
+.. sourcecode:: mako
+
+ <%def name="myfunc(x)">
+ this is myfunc, x is ${x}
+ </%def>
+
+ ${myfunc(7)}
+
+The %def tag is a lot more powerful than a plain Python def, as
+the Mako compiler provides many extra services with %def that
+you wouldn't normally have, such as the ability to export defs
+as template "methods", automatic propagation of the current
+``Context``, buffering/filtering/caching flags, and def calls
+with content, which enable packages of defs to be sent as
+arguments to other def calls (not as hard as it sounds). Get the
+full deal on what %def can do in :ref:`defs_toplevel`.
+
+<%namespace>
+-------------
+
+%namespace is Mako's equivalent of Python's ``import``
+statement. It allows access to all the rendering functions and
+metadata of other template files, plain Python modules, as well
+as locally defined "packages" of functions.
+
+.. sourcecode:: mako
+
+ <%namespace file="functions.html" import="*"/>
+
+The underlying object generated by %namespace, an instance of
+:class:`.mako.runtime.Namespace`, is a central construct used in
+templates to reference template-specific information such as the
+current URI, inheritance structures, and other things that are
+not as hard as they sound right here. Namespaces are described
+in :ref:`namespaces_toplevel`.
+
+<%inherit>
+----------
+
+Inherit allows templates to arrange themselves in **inheritance
+chains**. This is a concept familiar in many other template
+languages.
+
+.. sourcecode:: mako
+
+ <%inherit file="base.html"/>
+
+When using the %inherit tag, control is passed to the topmost
+inherited template first, which then decides how to handle
+calling areas of content from its inheriting templates. Mako
+offers a lot of flexbility in this area, including dynamic
+inheritance, content wrapping, and polymorphic method calls.
+Check it out in :ref:`inheritance_toplevel`.
+
+<%namespacename:defname>
+-------------------------
+
+As of Mako 0.2.3, any user-defined "tag" can be created against
+a namespace by using a tag with a name of the form
+``<%<namespacename>:<defname>>``. The closed and open formats of such a
+tag are equivalent to an inline expression and the ``<%call>``
+tag, respectively.
+
+.. sourcecode:: mako
+
+ <%mynamespace:somedef param="some value">
+ this is the body
+ </%mynamespace:somedef>
+
+To create custom tags which accept a body, see
+:ref:`defs_with_content`.
+
+<%call>
+-------
+
+The call tag is the "classic" form of a user-defined tag, and is
+roughly equiavlent to the ``<%namespacename:defname>`` syntax
+described above. This tag is also described in `defs_with_content`.
+
+<%doc>
+------
+
+The doc tag handles multiline comments:
+
+.. sourcecode:: mako
+
+ <%doc>
+ these are comments
+ more comments
+ </%doc>
+
+Also the ``##`` symbol as the first non-space characters on a line can be used for single line comments.
+
+<%text>
+-------
+
+This tag suspends the Mako lexer's normal parsing of Mako
+template directives, and returns its entire body contents as
+plain text. It is used pretty much to write documentation about
+Mako:
+
+.. sourcecode:: mako
+
+ <%text filter="h">
+ heres some fake mako ${syntax}
+ <%def name="x()">${x}</%def>
+ %CLOSETEXT
+
+Returning early from a template
+===============================
+
+Sometimes you want to stop processing a template or ``<%def>``
+method in the middle and just use the text you've accumulated so
+far. You can use a ````return```` statement inside a Python
+block to do that.
+
+.. sourcecode:: mako
+
+ % if not len(records):
+ No records found.
+ <% return %>
+ % endif
+
+Or perhaps:
+
+.. sourcecode:: mako
+
+ <%
+ if not len(records):
+ return
+ %>
diff --git a/doc/build/templates/site_base.mako b/doc/build/templates/site_base.mako
index 301c6a6..8ab31d9 100644
--- a/doc/build/templates/site_base.mako
+++ b/doc/build/templates/site_base.mako
@@ -1,14 +1,17 @@
<%text>#coding:utf-8
-<%inherit file="/base.html"/>
+<%inherit file="/root.html"/>
<%page cache_type="file" cached="True"/>
<%!
in_docs=True
%>
</%text>
+<%doc>
+## TODO: pdf
<div style="text-align:right">
<b>PDF Download:</b> <a href="${pathto('sqlalchemy_' + release.replace('.', '_') + '.pdf', 1)}">download</a>
</div>
+</%doc>
${'<%text>'}
${next.body()}
diff --git a/doc/build/unicode.rst b/doc/build/unicode.rst
index 8b13789..1615e7c 100644
--- a/doc/build/unicode.rst
+++ b/doc/build/unicode.rst
@@ -1 +1,5 @@
+.. _unicode_toplevel:
+===================
+The Unicode Chapter
+===================
diff --git a/doc/build/usage.rst b/doc/build/usage.rst
index 4e536b3..6c2dd90 100644
--- a/doc/build/usage.rst
+++ b/doc/build/usage.rst
@@ -1,3 +1,5 @@
+.. _usage_toplevel:
+
=====
Usage
=====
@@ -8,7 +10,7 @@ Basic Usage
This section describes the Python API for Mako templates. If you
are using Mako within a web framework such as Pylons, the work
of integrating Mako's API is already done for you, in which case
-you can skip to the next section, [syntax](rel:syntax).
+you can skip to the next section, :ref:`syntax_toplevel`.
The most basic way to create a template and render it is through
the :class:`.Template` class::
@@ -56,18 +58,18 @@ render with it, using the :meth:`~.Template.render_context` method::
Using File-Based Templates
===========================
-A `Template` can also load its template source code from a file,
-using the `filename` keyword argument::
+A :class:`.Template` can also load its template source code from a file,
+using the ``filename`` keyword argument::
from mako.template import Template
mytemplate = Template(filename='/docs/mytmpl.txt')
print mytemplate.render()
-For improved performance, a `Template` which is loaded from a
+For improved performance, a :class:`.Template` which is loaded from a
file can also cache the source code to its generated module on
the filesystem as a regular Python module file (i.e. a .py
-file). To do this, just add the `module_directory` argument to
+file). To do this, just add the ``module_directory`` argument to
the template::
from mako.template import Template
@@ -77,22 +79,22 @@ the template::
When the above code is rendered, a file
``/tmp/mako_modules/docs/mytmpl.txt.py`` is created containing the
-source code for the module. The next time a `Template` with the
+source code for the module. The next time a :class:`.Template` with the
same arguments is created, this module file will be
automatically re-used.
-Using :class:`.TemplateLookup`
-===============================
+Using TemplateLookup
+====================
All of the examples thus far have dealt with the usage of a
-single `Template` object. If the code within those templates
+single :class:`.Template` object. If the code within those templates
tries to locate another template resource, it will need some way
to find them, using simple URI strings. For this need, the
resolution of other templates from within a template is
-accomplished by the `TemplateLookup` class. This class is
+accomplished by the :class:`.TemplateLookup` class. This class is
constructed given a list of directories in which to search for
templates, as well as keyword arguments that will be passed to
-the `Template` objects it creates::
+the :class:`.Template` objects it creates::
from mako.template import Template
from mako.lookup import TemplateLookup
@@ -101,16 +103,16 @@ the `Template` objects it creates::
mytemplate = Template("""<%include file="header.txt"/> hello world!""", lookup=mylookup)
Above, we created a textual template which includes the file
-`header.txt`. In order for it to have somewhere to look for
-`header.txt`, we passed a `TemplateLookup` object to it, which
-will search in the directory `/docs` for the file `header.txt`.
+``"header.txt"``. In order for it to have somewhere to look for
+``"header.txt"``, we passed a :class:`.TemplateLookup` object to it, which
+will search in the directory ``/docs`` for the file ``"header.txt"``.
Usually, an application will store most or all of its templates
as text files on the filesystem. So far, all of our examples
have been a little bit contrived in order to illustrate the
basic concepts. But a real application would get most or all of
-its templates directly from the `TemplateLookup`, using the
-aptly named `get_template` method, which accepts the URI of the
+its templates directly from the :class:`.TemplateLookup`, using the
+aptly named :meth:`~.TemplateLookup.get_template` method, which accepts the URI of the
desired template::
from mako.template import Template
@@ -122,58 +124,58 @@ desired template::
mytemplate = mylookup.get_template(templatename)
print mytemplate.render(**kwargs)
-In the example above, we create a `TemplateLookup` which will
-look for templates in the `/docs` directory, and will store
-generated module files in the `/tmp/mako_modules` directory. The
+In the example above, we create a :class:`.TemplateLookup` which will
+look for templates in the ``/docs`` directory, and will store
+generated module files in the ``/tmp/mako_modules`` directory. The
lookup locates templates by appending the given URI to each of
its search directories; so if you gave it a URI of
-`/etc/beans/info.txt`, it would search for the file
-`/docs/etc/beans/info.txt`, else raise a `TopLevelNotFound`
+``/etc/beans/info.txt``, it would search for the file
+``/docs/etc/beans/info.txt``, else raise a :class:`.TopLevelNotFound`
exception, which is a custom Mako exception.
-When the lookup locates templates, it will also assign a `uri`
-property to the `Template` which is the uri passed to the
-`get_template()` call. `Template` uses this uri to calculate the
+When the lookup locates templates, it will also assign a ``uri``
+property to the :class:`.Template` which is the uri passed to the
+:meth:`~.TemplateLookup.get_template()` call. :class:`.Template` uses this uri to calculate the
name of its module file. So in the above example, a
-`templatename` argument of `/etc/beans/info.txt` will create a
-module file `/tmp/mako_modules/etc/beans/info.txt.py`.
+``templatename`` argument of ``/etc/beans/info.txt`` will create a
+module file ``/tmp/mako_modules/etc/beans/info.txt.py``.
Setting the Collection Size
---------------------------
-The `TemplateLookup` also serves the important need of caching a
+The :class:`.TemplateLookup` also serves the important need of caching a
fixed set of templates in memory at a given time, so that
successive uri lookups do not result in full template
compilations and/or module reloads on each request. By default,
-the `TemplateLookup` size is unbounded. You can specify a fixed
-size using the `collection_size` argument::
+the :class:`.TemplateLookup` size is unbounded. You can specify a fixed
+size using the ``collection_size`` argument::
mylookup = TemplateLookup(directories=['/docs'],
module_directory='/tmp/mako_modules', collection_size=500)
The above lookup will continue to load templates into memory
until it reaches a count of around 500. At that point, it will
-clean out a certain percentage of templates using a **least
-recently used** scheme.
+clean out a certain percentage of templates using a least
+recently used scheme.
Setting Filesystem Checks
--------------------------
-Another important flag on `TemplateLookup` is
-`filesystem_checks`. This defaults to `True`, and says that each
-time a template is returned by the `get_template()` method, the
+Another important flag on :class:`.TemplateLookup` is
+``filesystem_checks``. This defaults to ``True``, and says that each
+time a template is returned by the :meth:`~.TemplateLookup.get_template()` method, the
revision time of the original template file is checked against
the last time the template was loaded, and if the file is newer
will reload its contents and recompile the template. On a
-production system, setting `filesystem_checks` to `False` can
+production system, setting ``filesystem_checks`` to ``False`` can
afford a small to moderate performance increase (depending on
the type of filesystem used).
Using Unicode and Encoding
===========================
-Both `Template` and `TemplateLookup` accept `output_encoding`
-and `encoding_errors` parameters which can be used to encode the
+Both :class:`.Template` and :class:`.TemplateLookup` accept ``output_encoding``
+and ``encoding_errors`` parameters which can be used to encode the
output in any Python supported codec::
from mako.template import Template
@@ -184,24 +186,25 @@ output in any Python supported codec::
mytemplate = mylookup.get_template("foo.txt")
print mytemplate.render()
-When using Python 3, the `render()` method will return a `bytes`
-object, **if** `output_encoding` is set. Otherwise it returns a
-`string`.
+When using Python 3, the :meth:`~.Template.render` method will return a ``bytes``
+object, **if** ``output_encoding`` is set. Otherwise it returns a
+``string``.
-Additionally, the `render_unicode()` method exists which will
-return the template output as a Python `unicode` object, or in
-Python 3 a `string`::
+Additionally, the :meth:`~.Template.render_unicode()` method exists which will
+return the template output as a Python ``unicode`` object, or in
+Python 3 a ``string``::
print mytemplate.render_unicode()
-The above method disregards the output encoding keyword argument; you can encode yourself by saying::
+The above method disregards the output encoding keyword
+argument; you can encode yourself by saying::
print mytemplate.render_unicode().encode('utf-8', 'replace')
Note that Mako's ability to return data in any encoding and/or
-`unicode` implies that the underlying output stream of the
+``unicode`` implies that the underlying output stream of the
template is a Python unicode object. This behavior is described
-fully in [unicode](rel:unicode).
+fully in :ref:`unicode_toplevel`.
.. _handling_exceptions:
@@ -224,9 +227,9 @@ template filenames, line numbers, and code samples. All lines
within a stack trace which correspond to a Mako template module
will be converted to be against the originating template file.
-To format exception traces, the `text_error_template` and
-`html_error_template` functions are provided. They make usage of
-`sys.exc_info()` to get at the most recently thrown exception.
+To format exception traces, the :func:`.text_error_template` and
+:func:`.html_error_template` functions are provided. They make usage of
+``sys.exc_info()`` to get at the most recently thrown exception.
Usage of these handlers usually looks like::
from mako import exceptions
@@ -247,37 +250,37 @@ Or for the HTML render function::
except:
print exceptions.html_error_template().render()
-The `html_error_template` template accepts two options:
-specifying `full=False` causes only a section of an HTML
-document to be rendered. Specifying `css=False` will disable the
+The :func:`.html_error_template` template accepts two options:
+specifying ``full=False`` causes only a section of an HTML
+document to be rendered. Specifying ``css=False`` will disable the
default stylesheet from being rendered.
E.g.::
- print exceptions.html_error_template().render(full=False)
+ print exceptions.html_error_template().render(full=False)
The HTML render function is also available built-in to
-`Template` using the `format_exceptions` flag. In this case, any
+:class:`.Template` using the ``format_exceptions`` flag. In this case, any
exceptions raised within the **render** stage of the template
will result in the output being substituted with the output of
-`html_error_template`::
+:func:`.html_error_template`::
template = Template(filename="/foo/bar", format_exceptions=True)
print template.render()
Note that the compile stage of the above template occurs when
-you construct the `Template` itself, and no output stream is
+you construct the :class:`.Template` itself, and no output stream is
defined. Therefore exceptions which occur within the
lookup/parse/compile stage will not be handled and will
propagate normally. While the pre-render traceback usually will
not include any Mako-specific lines anyway, it will mean that
exceptions which occur previous to rendering and those which
occur within rendering will be handled differently...so the
-`try/except` patterns described previously are probably of more
+try/except patterns described previously are probably of more
general use.
The underlying object used by the error template functions is
-the `RichTraceback` object. This object can also be used
+the :class:`.RichTraceback` object. This object can also be used
directly to provide custom error views. Here's an example usage
which describes its general API::
@@ -293,9 +296,6 @@ which describes its general API::
print line, "\n"
print "%s: %s" % (str(traceback.error.__class__.__name__), traceback.error)
-Further information about `RichTraceback` is available within
-the module-level documentation for `mako.exceptions`.
-
Common Framework Integrations
=============================
@@ -307,12 +307,12 @@ WSGI
----
A sample WSGI application is included in the distrubution in the
-file `examples/wsgi/run_wsgi.py`. This runner is set up to pull
+file ``examples/wsgi/run_wsgi.py``. This runner is set up to pull
files from a `templates` as well as an `htdocs` directory and
includes a rudimental two-file layout. The WSGI runner acts as a
-fully functional standalone web server, using `wsgiutils` to run
+fully functional standalone web server, using ``wsgiutils`` to run
itself, and propagates GET and POST arguments from the request
-into the `Context`, can serve images, css files and other kinds
+into the :class:`.Context`, can serve images, css files and other kinds
of files, and also displays errors using Mako's included
exception-handling utilities.
@@ -320,11 +320,11 @@ Pygments
---------
A `Pygments <http://pygments.pocoo.org>`_-compatible syntax
-highlighting module is included under `mako.ext.pygmentplugin`.
+highlighting module is included under :mod:`mako.ext.pygmentplugin`.
This module is used in the generation of Mako documentation and
also contains various setuptools entry points under the heading
-`pygments.lexers`, including `mako`, `html+mako`, `xml+mako`
-(see the `setup.py` file for all the entry points).
+``pygments.lexers``, including ``mako``, ``html+mako``, ``xml+mako``
+(see the ``setup.py`` file for all the entry points).
Babel
------
@@ -334,11 +334,8 @@ templates via a `Babel`_ extractor
entry point under `mako.ext.babelplugin`.
Gettext messages are extracted from all Python code sections,
-even the more obscure ones such as [control
-structures](rel:syntax_control), [def tag function
-declarations](rel:defs), [call tag
-exprs](rel:defs_defswithcontent) and even [page tag
-args](rel:syntax_tags_page).
+including those of control lines and expressions embedded
+in tags.
`Translator
comments <http://babel.edgewall.org/wiki/Documentation/messages.html#comments-tags-and-translator-comments-explanation>`_
@@ -346,8 +343,10 @@ may also be extracted from Mako templates when a comment tag is
specified to `Babel`_ (such as with
the -c option).
-For example, a project '`myproj`' contains the following Mako
-template at myproj/myproj/templates/name.html::
+For example, a project ``"myproj"`` contains the following Mako
+template at ``myproj/myproj/templates/name.html``:
+
+.. sourcecode:: mako
<div id="name">
Name:
@@ -359,7 +358,7 @@ template at myproj/myproj/templates/name.html::
To extract gettext messages from this template the project needs
a Mako section in its `Babel Extraction Method Mapping
file <http://babel.edgewall.org/wiki/Documentation/messages.html#extraction-method-mapping-and-configuration>`_
-(typically located at myproj/babel.cfg)::
+(typically located at ``myproj/babel.cfg``)::
# Extraction from Python source files
@@ -370,9 +369,9 @@ file <http://babel.edgewall.org/wiki/Documentation/messages.html#extraction-meth
[mako: myproj/templates/**.html]
input_encoding = utf-8
-The Mako extractor supports an optional `input_encoding`
+The Mako extractor supports an optional ``input_encoding``
parameter specifying the encoding of the templates (identical to
-`Template`/`TemplateLookup`'s `input_encoding` parameter).
+:class:`.Template`/:class:`.TemplateLookup`'s ``input_encoding`` parameter).
Invoking `Babel`_'s extractor at the
command line in the project's root directory::
@@ -418,6 +417,9 @@ API Documentation
.. autoclass:: mako.template.Template
:members:
+.. autoclass:: mako.template.DefTemplate
+ :members:
+
.. autoclass:: mako.lookup.TemplateCollection
:members:
diff --git a/mako/template.py b/mako/template.py
index e78afcd..9a6c6c2 100644
--- a/mako/template.py
+++ b/mako/template.py
@@ -270,7 +270,7 @@ class Template(object):
return hasattr(self.module, "render_%s" % name)
def get_def(self, name):
- """Return a def of this template as a DefTemplate."""
+ """Return a def of this template as a :class:`.DefTemplate`."""
return DefTemplate(self, getattr(self.module, "render_%s" % name))