-
- ${content}
-
- % if (subsection and item.next and item.next.depth >= item.depth) or not subsection:
- % if paged:
- back to section top
- % else:
- back to section top
- % endif
- % endif
-
-
-%def>
-
-
-<%def name="formatplain()" filter="plainfilter">
- ${ caller.body() | h}
-%def>
-
-
-<%def name="codeline()" filter="trim,h">
- ${ caller.body() }
-%def>
-
-<%def name="code(title=None, syntaxtype='mako', html_escape=False, use_sliders=False)">
- <%!
- import pygments
- from pygments.formatters import HtmlFormatter
- from pygments.lexers import PythonLexer, HtmlLexer, IniLexer
- from mako.ext.pygmentplugin import MakoHtmlLexer
- lexers = {'mako':MakoHtmlLexer(), 'python':PythonLexer(), 'html':HtmlLexer(),
- 'ini':IniLexer()}
- %>
- <%
- lexer = lexers.get(syntaxtype, None)
- # dumb hack to print a %text> tag inside of a <%text> section
- content = re.sub(r'%CLOSETEXT', '%text>', capture(caller.body))
-
- if lexer is not None:
- content = pygments.highlight(content, lexer, HtmlFormatter())
- else:
- content = "
" + content + "
"
- %>
-
-
- % if title is not None:
- ${title}
- % endif
- ${ content }
-
+
+ % for i, (key, dummy) in enumerate(genindexentries):
+ ${i != 0 and '| ' or ''}${key}
+ % endfor
+
+
+
+ % for i, (key, entries) in enumerate(genindexentries):
+
- % if item.previous is not None:
- Previous: ${itemlink(item=item.previous, paged=paged, anchor=not paged, extension=extension)}
- % endif
-
- % if item.next is not None:
- ${item.previous is not None and "|" or ""}
- Next: ${itemlink(item=item.next, paged=paged, anchor=not paged, extension=extension)}
- % endif
-
-%def>
-
diff --git a/doc/build/unicode.rst b/doc/build/unicode.rst
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/doc/build/unicode.rst
@@ -0,0 +1 @@
+
diff --git a/doc/build/usage.rst b/doc/build/usage.rst
new file mode 100644
index 0000000..fb26f37
--- /dev/null
+++ b/doc/build/usage.rst
@@ -0,0 +1,471 @@
+=====
+Usage
+=====
+
+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).
+
+The most basic way to create a template and render it is through
+the :class:`.Template` class::
+
+ from mako.template import Template
+
+ mytemplate = Template("hello world!")
+ print mytemplate.render()
+
+Above, the text argument to :class:`.Template` is **compiled** into a
+Python module representation. This module contains a function
+called :meth:`~.Template.render_body()`, which produces the output of the
+template. When ``mytemplate.render()`` is called, Mako sets up a
+runtime environment for the template and calls the
+:meth:`~.Template.render_body()` function, capturing the output into a buffer and
+returning its string contents.
+
+
+The code inside the ``render_body()`` function has access to a
+namespace of variables. You can specify these variables by
+sending them as additional keyword arguments to the :meth:`~.Template.render`
+method::
+
+ from mako.template import Template
+
+ mytemplate = Template("hello, ${name}!")
+ print mytemplate.render(name="jack")
+
+The :meth:`~.Template.render` method calls upon Mako to create a
+:class:`.Context` object, which stores all the variable names accessible
+to the template and also stores a buffer used to capture output.
+You can create this :class:`.Context` yourself and have the template
+render with it, using the :meth:`~.Template.render_context` method::
+
+ from mako.template import Template
+ from mako.runtime import Context
+ from StringIO import StringIO
+
+ mytemplate = Template("hello, ${name}!")
+ buf = StringIO()
+ ctx = Context(buf, name="jack")
+ mytemplate.render_context(ctx)
+ print buf.getvalue()
+
+Using File-Based Templates
+===========================
+
+A `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
+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
+the template::
+
+ from mako.template import Template
+
+ mytemplate = Template(filename='/docs/mytmpl.txt', module_directory='/tmp/mako_modules')
+ print mytemplate.render()
+
+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
+same arguments is created, this module file will be
+automatically re-used.
+
+Using :class:`.TemplateLookup`
+===============================
+
+All of the examples thus far have dealt with the usage of a
+single `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
+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::
+
+ from mako.template import Template
+ from mako.lookup import TemplateLookup
+
+ mylookup = TemplateLookup(directories=['/docs'])
+ 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`.
+
+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
+desired template::
+
+ from mako.template import Template
+ from mako.lookup import TemplateLookup
+
+ mylookup = TemplateLookup(directories=['/docs'], module_directory='/tmp/mako_modules')
+
+ def serve_template(templatename, **kwargs):
+ 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
+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`
+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
+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`.
+
+Setting the Collection Size
+---------------------------
+
+The `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::
+
+ 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.
+
+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
+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
+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
+output in any Python supported codec::
+
+ from mako.template import Template
+ from mako.lookup import TemplateLookup
+
+ mylookup = TemplateLookup(directories=['/docs'], output_encoding='utf-8', encoding_errors='replace')
+
+ 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`.
+
+Additionally, the `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::
+
+ 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
+template is a Python unicode object. This behavior is described
+fully in [unicode](rel:unicode).
+
+.. _handling_exceptions:
+
+Handling Exceptions
+====================
+
+Template exceptions can occur in two distinct places. One is
+when you **lookup, parse and compile** the template, the other
+is when you **run** the template. Within the running of a
+template, exceptions are thrown normally from whatever Python
+code originated the issue. Mako has its own set of exception
+classes which mostly apply to the lookup and lexer/compiler
+stages of template construction. Mako provides some library
+routines that can be used to help provide Mako-specific
+information about any exception's stack trace, as well as
+formatting the exception within textual or HTML format. In all
+cases, the main value of these handlers is that of converting
+Python filenames, line numbers, and code samples into Mako
+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.
+Usage of these handlers usually looks like::
+
+ from mako import exceptions
+
+ try:
+ template = lookup.get_template(uri)
+ print template.render()
+ except:
+ print exceptions.text_error_template().render()
+
+Or for the HTML render function::
+
+ from mako import exceptions
+
+ try:
+ template = lookup.get_template(uri)
+ print template.render()
+ 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
+default stylesheet from being rendered.
+
+E.g.::
+
+ 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
+exceptions raised within the **render** stage of the template
+will result in the output being substituted with the output of
+`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
+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
+general use.
+
+The underlying object used by the error template functions is
+the `RichTraceback` object. This object can also be used
+directly to provide custom error views. Here's an example usage
+which describes its general API::
+
+ from mako.exceptions import RichTraceback
+
+ try:
+ template = lookup.get_template(uri)
+ print template.render()
+ except:
+ traceback = RichTraceback()
+ for (filename, lineno, function, line) in traceback.traceback:
+ print "File %s, line %s, in %s" % (filename, lineno, function)
+ 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
+=============================
+
+The Mako distribution includes a little bit of helper code for
+the purpose of using Mako in some popular web framework
+scenarios. This is a brief description of whats included.
+
+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
+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
+itself, and propagates GET and POST arguments from the request
+into the `Context`, can serve images, css files and other kinds
+of files, and also displays errors using Mako's included
+exception-handling utilities.
+
+Pygments
+---------
+
+A `Pygments `_-compatible syntax
+highlighting module is included under `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).
+
+Babel
+------
+
+Mako provides support for extracting gettext messages from
+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).
+
+`Translator
+comments `_
+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::
+
+
+ Name:
+ ## TRANSLATORS: This is a proper name. See the gettext
+ ## manual, section Names.
+ ${_('Francois Pinard')}
+
+
+To extract gettext messages from this template the project needs
+a Mako section in its `Babel Extraction Method Mapping
+file `_
+(typically located at myproj/babel.cfg)::
+
+ # Extraction from Python source files
+
+ [python: myproj/**.py]
+
+ # Extraction from Mako templates
+
+ [mako: myproj/templates/**.html]
+ input_encoding = utf-8
+
+The Mako extractor supports an optional `input_encoding`
+parameter specifying the encoding of the templates (identical to
+`Template`/`TemplateLookup`'s `input_encoding` parameter).
+
+Invoking `Babel`_'s extractor at the
+command line in the project's root directory::
+
+ myproj$ pybabel extract -F babel.cfg -c "TRANSLATORS:" .
+
+Will output a gettext catalog to stdout including the following::
+
+ #. TRANSLATORS: This is a proper name. See the gettext
+ #. manual, section Names.
+ #: myproj/templates/name.html:5
+ msgid "Francois Pinard"
+ msgstr ""
+
+This is only a basic example:
+`Babel`_ can be invoked from setup.py
+and its command line options specified in the accompanying
+setup.cfg via `Babel Distutils/Setuptools
+Integration `_.
+
+Comments must immediately precede a gettext message to be
+extracted. In the following case the TRANSLATORS: comment would
+not have been extracted:
+
+.. sourcecode:: mako
+
+
+ ## TRANSLATORS: This is a proper name. See the gettext
+ ## manual, section Names.
+ Name: ${_('Francois Pinard')}
+
Insanely Fast. An included bench suite, adapted from a suite included with Genshi, has these results for a simple three-sectioned layout:
-
-
Mako:
0.66 ms
-
Cheetah:
0.74 ms
-
Django:
5.43 ms
-
Myghty:
5.25 ms
-
Genshi:
12.53 ms
-
Kid:
19.12 ms
-
-
-
-- Super-simple API. For basic usage, just one class, `Template` is needed:
-
- from mako.template import Template
- print Template("hello ${data}!").render(data="world")
-
-- To manage many templates, leveraging industrial strength module generation and management code adapted from Myghty, use the `TemplateLookup` class:
-
- from mako.lookup import TemplateLookup
- lookup = TemplateLookup(directories=['/my/htmlfiles'])
- template = lookup.get_template('index.html')
- print template.render(data="foo")
-
-- Mako's syntax borrows from the best ideas of many others, including:
-
- - Django Templates
- - Myghty / Mason
- - Cheetah
- - Genshi
- - Java Server Pages
- - Struts Tiles
-
-- Standard template features:
- - control structures
-
- % if len(v) > 5:
- % for x in range(1,5):
- hi ${x}
- % endfor
- % endif
-
- - straight python code:
-
- <%
- data = handle.lookup()
- view = [d.name for d in data]
- %>
-
- - callable blocks, with or without arguments, which also pull names from the enclosing scope:
-
- # define:
- <%def name="foo(x, y)">
- hi im foo ${x} ${y} ${z}
- %def>
-
- # then call:
- ${foo(4,5)}
-
- - multi-zoned page inheritance
- - "component-calls-with-content" - call any def, nesting any number locally-defined blocks of text as arguments. This is the basis for creating custom tags:
-
- # define:
- <%def name="foo(x, y)">
- ${head()}
- foo ${x} {$y}
- ${body()}
- %def>
-
- # then call, defining two more blocks
- <%call expr="foo(3, 4)">
- <%def name="head">
- the header
- %def>
- main body
- %call>
-
- - filters, either the standard builtins or custom functions, applicable to any expression or `<%def>` definition:
-
- ${"some text" | h}
-
- <%def name="foo" filter="filter1, x">
- ...
- %def>
-
- - custom tags can be created as templated components, or Python modules containing callables. Whole sets of custom tags can be imported into the current template's namespace using the `<%namespace>` tag.
- - caching built in from the ground up. any template or block of text within can be cached using memory, file, DBM or memcached backends.
-
-## Language
-
-### Control Structures
-
-Control structures use the % operator. % can start anywhere on the line, preceded by only whitespace. Blocks are terminated by name-qualified terminators.
-
- % for item in items:
- % if foo:
- ${item}
- some text
- % endif
- % endfor
-
-The amount of whitespace before the % and after the % before the code starts is not significant.
-
-Myghty style:
-
- % if x:
- % if y:
- % endif
- % endif
-
-"Cheetah" style:
-
- %if x:
- %if y:
- %endif
- %endif
-
-Messy style (you probably wouldn't want to code this way for readablity):
-
- %if x:
- %if y:
- % endif
- % endif
-
-### Comments
-
-Work similarly to %, using the # tag:
-
-
- # this is a comment.
-
-
-### Truncating Newlines
-
-End any line with a backslash (\\) to suppress the newline at the end:
-
- % for x in [1,2,3]:\
- ${x} \
- % endfor
-
-Produces the output:
-
- 1 2 3
-
-The newline truncator is particularly important for producing plaintext documents such as emails, as well as preformatted sections of HTML (i.e. using `
`).
-
-### Expressions
-
-Expressions usually use ${expr} syntax, and compile into literal Python.
-
- ${someexpression}
-
- ${"foo" + "bar"}
-
-### Variable Namespace
-
-A template executes with a single contextual dictionary. This dictionary is completely transparent in the template itself. AST parsing of all embedded Python is performed in order to locate all referenced variable names, which are pre-declared from the dictionary at runtime (or a special "undefined" value if not present) before template-generated Python is executed. So when a variable "x" is referenced, the searched hierarchy is:
-
-- Variables declared locally, or as part of a control structure (like say, a for loop)
-- Variables declared in an enclosing scope.
-- Variables declared in the template at the module-level.
-- Names within the current context object.
-
-Notice that the context is the lowest priority for scope. This is to allow the most predictable behavior; when you create a template or component, the variables that are explicitly present regardless of the context's contents form part of the construction of that component. It should not be possible to place a name into the context that causes code which was written against an explicit scope to suddenly function differently.
-
-When variables from the context are what's specifically needed, just call them from the context explicitly:
-
- ${context['some key']}
-
-A convenience object `args` is also available which provides attribute-style access:
-
- args.mykey
-
-### Embedding Python
-#### Inline
-
-Inline Python is embedded via the <% %> tags. This is straight python so the whitespace is significant. You can emit text via the `write()` method on the context.
-
-
-
some table
-
- <%
- for x in ["one", "two", "three"]:
- context.write("
%s
" % x)
- %>
-
-
-
-Remember that you can reference any variable name from the template's context, and it will be pulled from the context automatically.
-
-Context:
-
- {'x':'one', 'y':'two'}
-
-Template:
-
- <%
- context.write("X is " + x + "\n")
- y = "hi there"
- context.write("Y is " + y + "\n")
- %>
-
-Produces:
-
- X is one
- Y is hi there
-
-The scoping rules for variable assignment within blocks of Python are the same as that for Python callables; if you assign to a variable name, that variable becomes bound to the local scope, and you cannot access it in the block before that assignment, even if it is part of the context that was sent to the template. (We tried different combinations in this area, trying to allow a reference to the enclosing scope which can be overridden through assignment; but it quickly leads to inconsistent behaviors...Python has got it right !). If you *do* want to use a variable from the context, then reassign to it locally, just assign it from the context first:
-
- <%
- # pull y from the context.
- y = context['y']
- %>
- y is ${y}
- <%
- # now assign something different to y.
- y = "hi there"
- %>
- y is ${y}
-
-#### Module Level
-
-Module level Python is declared by the <%! %> tags. Python in these blocks occurs at module import time (i.e. global scope)
-
- <%!
- import mystuff
- def writefoo(text):
- return "foo is " +text
- %>
-
- hello ${writefoo('jack')}
-
-
-### File Includes
-
-Use the <%include> tag.
-
- <%include file="somefile.txt"/>
-
-This tag also can handle expressions:
-
- <%include file="${filename}"/>
-
-In fact every <%tag> can use expressions (i.e. ${}) inside of their quoted sections.
-
-The include tag requires that the template being called has a `TemplateLookup` available with which to locate the included template.
-
-Add the `import="true"` flag to the `<%include>` tag and when you include the file, all the `<%def>` and `<%namespace>` sections declared in that file (described later) are pulled into the local namespace of the template, as though they were declared locally:
-
- <%include file="somefile.html" import="true"/>
-
-### Components
-
-The component is the single tag used to demarcate any block of text and/or code. It exists within generated Python as a callable function.
-
- <%def name="hello">
- hello world
- %def>
-
-They are normally called as expressions.
-
- the component: ${hello()}
-
-A `<%def>` can be declared anywhere inside a template, and becomes available throughout the template, including above where it was declared. The callable generated by `<%def>` gets generated outside of the enclosing template's callable. The name of the callable is then placed in the variable namespace of the parent component.
-
-Components have access to the current contextual namespace in exactly the same way their parent template does.
-
- Hello there ${username}, how are ya. Lets see what your account says:
-
- ${account()}
-
- <%def name="account">
- Account for ${username}:
-
- % for row in accountdata:
- Value: ${row}
- % endfor
- %def>
-
-You can also pass arguments to a component, which show up in the component's variable namespace overriding whatever is in the enclosing namespace:
-
- ${account(name='john')}
-
- <%def name="account">
- Hi ${name}
- %def>
-
-If you want your component to have positional arguments, you can declare them:
-
- <%def name="account(accountname, type)">
- account name: ${accountname}, type ${type}
- %def>
-
-As well as keyword arguments explicitly declared, using normal Python conventions:
-
- <%def name="account(accountname, type='personal')">
- account name: ${accountname}, type ${type}
- %def>
-
-When you declare explicit arguments in your component signature, they are required following normal Python conventions. This is in contrast to using variable names implicitly from the template's context, which produces `None` if the name doesn't exist. Additionally, explicitly declared arguments are handy in case you have the same names declared at the module level, and you'd like to insure that you get those arguments from the component call itself.
-
-#### Calling Components from Other Files
-
-Calling a component from another file differs from a regular `<%include>`, in that you are calling a specific component declared in that template, not the template body itself.
-
-First, load the file you want into a "namespace":
-
- <%namespace name="mystuff" file="mystuff.html"/>
-
-The namespace tag is declared once per template, and adds a local variable "mystuff" to the current scope.
-
-Then, just call the components off of `mystuff`:
-
- ${mystuff.somecomponent(x=5,y=7)}
-
-#### Components within Components
-
-The component model is totally recursive. Declaring `<%def>` inside another `<%def>` leads it to be local to its parent:
-
- <%def name="mycomponent">
- <%def name="subcomponent">
- a sub component
- %def>
-
- im the component, and the subcomopnent is ${subcomponent()}
- %def>
-
-The recursive component model becomes very handy for doing layouts, including usage within inheriting templates.
-
-#### Calling a component with embedded content and/or other components
-
-A flip-side to component within component is a component call with content. This is where you call a component, and at the same time declare a block of content that can be used by the component being called. This is the basic method used to declare "custom tags". To achieve this, use the `<%call>` tag instead of the regular expression syntax. By default, the body of content is assigned to the name `body`:
-
- <%def name="buildtable">
-
-
- ${body()}
-
-
- %def>
-
- <%call expr="buildtable">
- I am the table body.
- %call>
-
-This produces the output:
-
-
-
- I am the table body.
-
-
-
-The `body` name is executed each time its referenced. This means you can use component-call-with-content to build iterators, conditionals, etc:
-
- <%def name="lister(count)">
- % for x in range(1,count):
- ${body()}
- % endfor
- %def>
-
- <%call expr="lister(3)">
- hi
- %call>
-
-Produces:
-
- hi
- hi
- hi
-
-A custom "conditional" tag:
-
- <%def name="conditional(expr)">
- % if expr:
- ${body()}
- %
- %def>
-
- <%call expr="conditional(4==4)">
- im the result
- %call>
-
-Produces:
-
- im the result
-
-Since `body` is a callable, the hosting component can pass arguments:
-
- <%def name="layoutdata(somedata)">
-
-
-If you combine nested components with the component call with content, you can build whole layouts quite easily:
-
- <%def name="layout">
- # a layout component
-
-
- ${header()}
-
-
- ${sidebar()}
-
-
- ${body()}
-
-
- %def>
-
- # calls the layout component
- <%call expr="layout">
- <%def name="header">
- I am the header
- %def>
- <%def name="sidebar">
-
-
sidebar 1
-
sidebar 2
-
- %def>
-
- this is the body
- %call>
-
-The above layout would produce:
-
-
-
- I am the header
-
-
-
-
sidebar 1
-
sidebar 2
-
-
-
- this is the body
-
-
-
-### Inheritance
-
-Inheritance allows you to specify another template file that should take control of execution, using the current template's namespace. This is provided via the <%inherit> tag. This works similarly to the component call with content example above, where `body` is the main body of the template and you can also define other `<%def>` sections:
-
- # page.html:
-
- <%inherit name="base.html"/>
- <%def name="header">
- this is the header
- %def>
-
- I am the body
-
- <%def name="footer">
- this is the footer
- %def>
-
- # base.html:
-
-
-
-
-
- I am the body
-
- this is the footer
-
-
-
-The inheritance of the parent template occurs *where you put the inherit tag.* This means whatever content is above the inherit tag gets executed normally, without any inheritance. It also means you can inherit *dynamically!*
-
- <%
- if layout=='green':
- inheritfrom = 'greentmpl.html'
- else:
- inheritfrom = 'normaltmpl.html'
- %>
- <%inherit name="${inheritfrom}"/>
-
-### Page-level arguments
-
-As components can declare optinally explicit argument signatures, so can your template, using the `<%page>` tag:
-
- <%page arguments="(arg1, arg2, arg3=None)"/>
-
-The named arguments are pulled from the incoming context dictionary, overriding any module-level declared arguments. It also serves as a way to declare certain context arguments as required.
-
-### Filters
-
-Filters are callable functions that receive a single textual argument as a string, and return a new textual string as output. They are called using the `|` operator in expressions:
-
- ${"this is some text" | html}
-
-Or using the `filter` keyword for a `<%def>` or `<%call>` directive:
-
- <%def name="mycomp" filter="html">
- %def>
-
-Standard built-in filters are included: `html`, `xml`, `url`.
-
-Creating your own filters is easy. Any callable that is in the template's namespace can be used, or you can declare functions:
-
- <%|
- def myfilter(text):
- return "text" + text + "filtered"
- %>
-
- ${"hiya" | myfilter}
-
-Filters can also be defined using the `<%def>` tag. The text to be filtered is placed into the name 'text':
-
- <%def myfilter>
- text${text}filtered
- %def>
-
- ${"hiya" | myfilter}
-
-Filters can take arguments ! Using a python function:
-
- <%|
- def pythonfilter(text, arg1, arg2='foo'):
- return "text" + text + "filtered"
- %>
- ${"hiya" | pythonfilter('hello', 'world')}
-
-Or a `<%def>`:
-
- <%def componentfilter(arg1, arg2='foo')>
- text${text}filtered
- %def>
-
- ${"hiya" | componentfilter('hello', 'world')}
-
-### Caching
-
-Any template or component can be cached using the `cache` argument to the `%page` or `%def` directives:
-
- <%page cache="true"/>
-
- template text
-
- <%def name="mycomp" cache="true" cache_timeout="30" cache_type="memory">
- other text
- %def>
-
-Cache arguments:
-- cache="false|true" - turn caching on
-- cache_timeout - number of seconds in which to invalidate the cached data
-- cache_type - type of caching. `memory`, `file`, `dbm`, or `memcached`.
-
-### Namespaces
-
-Namespaces are used to organize groups of components into categories, and also to "import" components from other files so that you don't have to type the full filename of the remote component file.
-
-If the file `components.html` defines these two components:
-
- # components.html
- <%def name="comp1">
- this is comp1
- %def>
-
- <%def name="comp2">
- this is comp2
- %def>
-
-You can make another file, for example `index.html`, that pulls those two components into a namespace called `comp`:
-
- # index.html
- <%namespace name="comp" file="components.html"/>
-
- Heres comp1: ${comp.comp1()}
- Heres comp2: ${comp.comp2()}
-
-The `<%namespace>` tag is more powerful than that. You can also declare `<%defs>` within the namespace:
-
- # define a namespace
- <%namespace name="stuff">
- <%def name="comp1">
- comp1
- %def>
- %namespace>
-
- # then call it
- ${stuff:comp1()}
-
-Namespaces can also import modules containing regular Python callables. These callables need to take at least one argument, `context`:
-
-A module file `some/module.py` might contain the callable:
-
- def my_tag(context):
- context.write("hello world")
-
-A template can use this module via:
-
- <%namespace name="hw" module="some.module"/>
-
- ${hw.my_tag()}
-
-Note that the `context` argument is not needed in the call; the `namespace` tag creates a locally-scoped callable which takes care of it.
-
-
-
-
diff --git a/mako/exceptions.py b/mako/exceptions.py
index b9df87e..5976d65 100644
--- a/mako/exceptions.py
+++ b/mako/exceptions.py
@@ -48,33 +48,10 @@ class TopLevelLookupException(TemplateLookupException):
pass
class RichTraceback(object):
- """pulls the current exception from the sys traceback and extracts
+ """Pulls the current exception from the sys traceback and extracts
Mako-specific template information.
- Usage:
-
- RichTraceback()
-
- Properties:
-
- error - the exception instance.
- message - the exception error message as unicode
- source - source code of the file where the error occured.
- if the error occured within a compiled template,
- this is the template source.
- lineno - line number where the error occured. if the error
- occured within a compiled template, the line number
- is adjusted to that of the template source
- records - a list of 8-tuples containing the original
- python traceback elements, plus the
- filename, line number, source line, and full template source
- for the traceline mapped back to its originating source
- template, if any for that traceline (else the fields are None).
- reverse_records - the list of records in reverse
- traceback - a list of 4-tuples, in the same format as a regular
- python traceback, with template-corresponding
- traceback records replacing the originals
- reverse_traceback - the traceback list in reverse
+ See the usage examples in :ref:`handling_exceptions`.
"""
def __init__(self, error=None, traceback=None):
diff --git a/mako/template.py b/mako/template.py
index ba4976c..0e99acf 100644
--- a/mako/template.py
+++ b/mako/template.py
@@ -14,7 +14,74 @@ import imp, os, re, shutil, stat, sys, tempfile, time, types, weakref
class Template(object):
- """a compiled template"""
+ """Represents a compiled template.
+
+ :class:`.Template` includes a reference to the original
+ template source (via the ``.source`` attribute)
+ as well as the source code of the
+ generated Python module (i.e. the ``.code`` attribute),
+ as well as a reference to an actual Python module.
+
+ :class:`.Template` is constructed using either a literal string
+ representing the template text, or a filename representing a filesystem
+ path to a source file.
+
+ :param text: textual template source. This argument is mutually exclusive
+ versus the "filename" parameter.
+
+ :param filename: filename of the source template. This argument is
+ mutually exclusive versus the "text" parameter.
+
+ :param buffer_filters:
+
+ :param cache_dir:
+
+ :param cache_enabled:
+
+ :param cache_type:
+
+ :param cache_url:
+
+ :param default_filters:
+
+ :param disable_unicode:
+
+ :param encoding_errors:
+
+ :param error_handler:
+
+ :param format_exceptions: if ``True``, exceptions which occur during
+ the render phase of this template will be caught and
+ formatted into an HTML error page, which then becomes the
+ rendered result of the :meth:`render` call. Otherwise,
+ runtime exceptions are propagated outwards.
+
+ :param imports:
+
+ :param input_encoding:
+
+ :param lookup:
+
+ :param module_directory: Filesystem location where generated Python
+ module files will be placed.
+
+ :param module_filename:
+
+ :param output_encoding:
+
+ :param preprocessor:
+
+ :param strict_undefined:
+
+ :param uri: string uri or other identifier for this template. If not provided,
+ the uri is generated from the filesystem path, or from the
+ in-memory identity of a non-file-based template. The primary usage of the
+ uri is to generate the file path of the generated Python module file,
+ if ``module_directory`` is specified.
+
+
+ """
+
def __init__(self,
text=None,
filename=None,
@@ -37,22 +104,6 @@ class Template(object):
imports=None,
preprocessor=None,
cache_enabled=True):
- """Construct a new Template instance using either literal template
- text, or a previously loaded template module
-
- :param text: textual template source, or None if a module is to be
- provided
-
- :param uri: the uri of this template, or some identifying string.
- defaults to the full filename given, or "memory:(hex id of this
- Template)" if no filename
-
- :param filename: filename of the source template, if any
-
- :param format_exceptions: catch exceptions and format them into an
- error display template
- """
-
if uri:
self.module_id = re.sub(r'\W', "_", uri)
self.uri = uri
@@ -161,6 +212,7 @@ class Template(object):
self._code = code
ModuleInfo(module, None, self, filename, code, None)
return module
+
@property
def source(self):
"""return the template source code for this Template."""
--
cgit v1.2.1