diff options
author | Vincent Férotin <vincent.ferotin@gmail.com> | 2012-05-14 19:34:01 +0200 |
---|---|---|
committer | Vincent Férotin <vincent.ferotin@gmail.com> | 2012-05-14 19:34:01 +0200 |
commit | 6c1f7da909b2816527774b8426000e34dd786b45 (patch) | |
tree | a29dd110fb376bdb2a886b055c15d8d8517c5141 | |
parent | d8af6f5e00d57ab4f9bb6bc01947b137ac9a984a (diff) | |
download | external_python_mako-6c1f7da909b2816527774b8426000e34dd786b45.tar.gz external_python_mako-6c1f7da909b2816527774b8426000e34dd786b45.tar.bz2 external_python_mako-6c1f7da909b2816527774b8426000e34dd786b45.zip |
Add some `reStructuredText` (or `Sphinx` related) markups:
add more litterals, systematicaly use ``.. sourcecode::`` before code samples,
add some ``:func:``, ``:class:`` and so on, fix some links, etc.
-rw-r--r-- | doc/build/caching.rst | 53 | ||||
-rw-r--r-- | doc/build/defs.rst | 4 | ||||
-rw-r--r-- | doc/build/filtering.rst | 26 | ||||
-rw-r--r-- | doc/build/index.rst | 1 | ||||
-rw-r--r-- | doc/build/inheritance.rst | 90 | ||||
-rw-r--r-- | doc/build/namespaces.rst | 16 | ||||
-rw-r--r-- | doc/build/runtime.rst | 15 | ||||
-rw-r--r-- | doc/build/syntax.rst | 70 | ||||
-rw-r--r-- | doc/build/unicode.rst | 29 | ||||
-rw-r--r-- | doc/build/usage.rst | 104 | ||||
-rw-r--r-- | mako/cache.py | 9 | ||||
-rw-r--r-- | mako/exceptions.py | 8 | ||||
-rw-r--r-- | mako/lookup.py | 44 | ||||
-rw-r--r-- | mako/runtime.py | 62 | ||||
-rw-r--r-- | mako/template.py | 94 |
15 files changed, 350 insertions, 275 deletions
diff --git a/doc/build/caching.rst b/doc/build/caching.rst index 01e98a5..31bbba4 100644 --- a/doc/build/caching.rst +++ b/doc/build/caching.rst @@ -78,12 +78,14 @@ caching can be configured using these arguments: * ``cache_enabled`` - Setting this to ``False`` will disable all caching functionality when the template renders. Defaults to ``True``. - e.g.:: + e.g.: - lookup = TemplateLookup( - directories='/path/to/templates', - cache_enabled = False - ) + .. sourcecode:: python + + lookup = TemplateLookup( + directories='/path/to/templates', + cache_enabled = False + ) * ``cache_impl`` - The string name of the cache backend to use. This defaults to ``'beaker'``, which has historically @@ -92,13 +94,15 @@ caching can be configured using these arguments: For example, here's how to use the upcoming `dogpile.cache <http://dogpilecache.readthedocs.org>`_ - backend:: + backend: - lookup = TemplateLookup( - directories='/path/to/templates', - cache_impl = 'dogpile.cache', - cache_args = {'regions':my_dogpile_regions} - ) + .. sourcecode:: python + + lookup = TemplateLookup( + directories='/path/to/templates', + cache_impl = 'dogpile.cache', + cache_args = {'regions':my_dogpile_regions} + ) * ``cache_args`` - A dictionary of cache parameters that will be consumed by the cache backend. See @@ -116,7 +120,7 @@ The actual arguments understood are determined by the backend. * :ref:`beaker_backend` - Includes arguments understood by Beaker. -* :ref:`mako_plugin` - Includes arguments understood by +* :ref:`dogpile.cache_backend` - Includes arguments understood by dogpile.cache. .. _beaker_backend: @@ -135,7 +139,9 @@ region that will store content in a memory-based dictionary, expiring after 60 seconds. The other is a Memcached region, where values should expire in five minutes. To configure our :class:`.TemplateLookup`, first we get a handle to a -:class:`beaker.cache.CacheManager`:: +:class:`beaker.cache.CacheManager`: + +.. sourcecode:: python from beaker.cache import CacheManager @@ -212,6 +218,8 @@ without the ``cache_`` prefix in the ``cache_args`` dictionary: an exception is thrown. Available as ``dir`` in the ``cache_args`` dictionary. +.. _dogpile.cache_backend: + Using the dogpile.cache Backend -------------------------------- @@ -225,7 +233,7 @@ Programmatic Cache Access ========================= The :class:`.Template`, as well as any template-derived :class:`.Namespace`, has -an accessor called ``cache`` which returns the ``Cache`` object +an accessor called ``cache`` which returns the :class:`.Cache` object for that template. This object is a facade on top of the underlying :class:`.CacheImpl` object, and provides some very rudimental capabilities, such as the ability to get and put arbitrary @@ -257,7 +265,9 @@ sections programmatically: template.cache.invalidate('somekey') You can access any special method or attribute of the :class:`.CacheImpl` -itself using the ``impl`` attribute:: +itself using the :attr:`impl <.Cache.impl>` attribute: + +.. sourcecode:: python template.cache.impl.do_something_special() @@ -278,12 +288,14 @@ provide the default implementation. A :class:`.CacheImpl` class is acquired by Mako using a ``pkg_resources`` entrypoint, using the name given as the ``cache_impl`` argument to :class:`.Template` or :class:`.TemplateLookup`. This entry point can be -installed via the standard setuptools/``setup()`` procedure, underneath -the EntryPoint group named ``"mako.cache"``. It can also be +installed via the standard `setuptools`/``setup()`` procedure, underneath +the `EntryPoint` group named ``"mako.cache"``. It can also be installed at runtime via a convenience installer :func:`.register_plugin` which accomplishes essentially the same task. -An example plugin that implements a local dictionary cache:: +An example plugin that implements a local dictionary cache: + +.. sourcecode:: python from mako.cache import Cacheimpl, register_plugin @@ -311,7 +323,9 @@ An example plugin that implements a local dictionary cache:: # optional - register the class locally register_plugin("simple", __name__, "SimpleCacheImpl") -Enabling the above plugin in a template would look like:: +Enabling the above plugin in a template would look like: + +.. sourcecode:: python t = Template("mytemplate", file="mytemplate.html", @@ -371,3 +385,4 @@ API Reference .. autoclass:: mako.ext.beaker_cache.BeakerCacheImpl :members: :show-inheritance: + diff --git a/doc/build/defs.rst b/doc/build/defs.rst index 742147d..8916c39 100644 --- a/doc/build/defs.rst +++ b/doc/build/defs.rst @@ -94,7 +94,7 @@ To import another template, use the ``<%namespace>`` tag: <%namespace name="mystuff" file="mystuff.html"/> -The above tag adds a local variable "mystuff" to the current +The above tag adds a local variable ``mystuff`` to the current scope. Then, just call the defs off of ``mystuff``: @@ -195,7 +195,7 @@ the following code will raise an error: %> </%def> -...because the assignment to ``x`` declares x as local to the +...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. diff --git a/doc/build/filtering.rst b/doc/build/filtering.rst index 95f836c..cb8bb92 100644 --- a/doc/build/filtering.rst +++ b/doc/build/filtering.rst @@ -88,12 +88,12 @@ Result: .. _filtering_default_filters: -The default_filters Argument ----------------------------- +The ``default_filters`` Argument +-------------------------------- In addition to the ``expression_filter`` argument, the -``default_filters`` argument to both ``Template`` and -``TemplateLookup`` can specify filtering for all expression tags +``default_filters`` argument to both :class:`.Template` and +:class:`.TemplateLookup` can specify filtering for all expression tags at the programmatic level. This array-based argument, when given its default argument of ``None``, will be internally set to ``["unicode"]`` (or ``["str"]`` on Python 3), except when @@ -147,8 +147,8 @@ The above will generate templates something like this: def render_body(context): context.write(myfilter(unicode("some text"))) -Turning off Filtering with the "n" filter ------------------------------------------- +Turning off Filtering with the ``n`` filter +-------------------------------------------- In all cases the special ``n`` filter, used locally within an expression, will **disable** all filters declared in the @@ -178,7 +178,7 @@ given list of filter functions to the output of the ``%def``: <b>this is bold</b> </%def> -When the filter attribute is applied to a def as above, the def +When the ``filter`` attribute is applied to a def as above, the def is automatically **buffered** as well. This is described next. Buffering @@ -187,7 +187,7 @@ Buffering One of Mako's central design goals is speed. To this end, all of the textual content within a template and its various callables is by default piped directly to the single buffer that is stored -within the ``Context`` object. While this normally is easy to +within the :class:`.Context` object. While this normally is easy to miss, it has certain side effects. The main one is that when you call a def using the normal expression syntax, i.e. ``${somedef()}``, it may appear that the return value of the @@ -243,8 +243,8 @@ which is then popped off the stack and its value returned. The speed hit inherent in buffering the output of a def is also apparent. -Note that the ``filter`` argument on %def also causes the def to -be buffered. This is so that the final content of the %def can +Note that the ``filter`` argument on ``%def`` also causes the def to +be buffered. This is so that the final content of the ``%def`` can be delivered to the escaping function in one batch, which reduces method calls and also produces more deterministic behavior for the filtering function itself, which can possibly @@ -281,7 +281,7 @@ Decorating =========== This is a feature that's new as of version 0.2.5. Somewhat like -a filter for a %def but more flexible, the ``decorator`` +a filter for a ``%def`` but more flexible, the ``decorator`` argument to ``%def`` allows the creation of a function that will work in a similar manner to a Python decorator. The function can control whether or not the function executes. The original @@ -314,7 +314,7 @@ simplicities' sake: The above template will return, with more whitespace than this, ``"BAR this is foo BAR"``. The function is the render callable itself (or possibly a wrapper around it), and by default will -write to the context. To capture its output, use the ``capture`` +write to the context. To capture its output, use the :func:`.capture` callable in the ``mako.runtime`` module (available in templates as just ``runtime``): @@ -335,6 +335,6 @@ as just ``runtime``): The decorator can be used with top-level defs as well as nested defs, and blocks too. Note that when calling a top-level def from the -``Template`` API, i.e. ``template.get_def('somedef').render()``, +:class:`.Template` API, i.e. ``template.get_def('somedef').render()``, the decorator has to write the output to the ``context``, i.e. as in the first example. The return value gets discarded. diff --git a/doc/build/index.rst b/doc/build/index.rst index f068adb..01d0f17 100644 --- a/doc/build/index.rst +++ b/doc/build/index.rst @@ -19,3 +19,4 @@ Indices and tables * :ref:`genindex` * :ref:`search` + diff --git a/doc/build/inheritance.rst b/doc/build/inheritance.rst index 0e0e80d..96072d5 100644 --- a/doc/build/inheritance.rst +++ b/doc/build/inheritance.rst @@ -5,10 +5,10 @@ Inheritance =========== .. note:: Most of the inheritance examples here take advantage of a feature that's - new in Mako as of version 0.4.1 called the "block". This tag is very similar to - the "def" tag but is more streamlined for usage with inheritance. Note that - all of the examples here which use blocks can also use defs instead. Contrasting - usages will be illustrated. + new in Mako as of version 0.4.1 called the "block". This tag is very similar to + the "def" tag but is more streamlined for usage with inheritance. Note that + all of the examples here which use blocks can also use defs instead. Contrasting + usages will be illustrated. Using template inheritance, two or more templates can organize themselves into an **inheritance chain**, where content and @@ -57,39 +57,39 @@ And ``base.html``, the inherited template: Here is a breakdown of the execution: -* When ``index.html`` is rendered, control immediately passes to - ``base.html``. -* ``base.html`` then renders the top part of an HTML document, - then invokes the ``<%block name="header">`` block. It invokes the - underlying ``header()`` function off of a built-in namespace - called ``self`` (this namespace was first introduced in the - Namespaces chapter in :ref:`namespace_self`). Since - ``index.html`` is the topmost template and also defines a block - called ``header``, it's this ``header`` block that ultimately gets - executed -- instead of the one that's present in ``base.html``. -* Control comes back to ``base.html``. Some more HTML is - rendered. -* ``base.html`` executes ``self.body()``. The ``body()`` - function on all template-based namespaces refers to the main - body of the template, therefore the main body of - ``index.html`` is rendered. -* When ``<%block name="header">`` is encountered in ``index.html`` - during the ``self.body()`` call, a conditional is checked -- does the - current inherited template, i.e. ``base.html``, also define this block? If yes, - the ``<%block>`` is **not** executed here -- the inheritance - mechanism knows that the parent template is responsible for rendering - this block (and in fact it already has). In other words a block - only renders in its *basemost scope*. -* Control comes back to ``base.html``. More HTML is rendered, - then the ``<%block name="footer">`` expression is invoked. -* The ``footer`` block is only defined in ``base.html``, so being - the topmost definition of ``footer``, it's the one that - executes. If ``index.html`` also specified ``footer``, then - its version would **override** that of the base. -* ``base.html`` finishes up rendering its HTML and the template - is complete, producing: - - .. sourcecode:: html +#. When ``index.html`` is rendered, control immediately passes to + ``base.html``. +#. ``base.html`` then renders the top part of an HTML document, + then invokes the ``<%block name="header">`` block. It invokes the + underlying ``header()`` function off of a built-in namespace + called ``self`` (this namespace was first introduced in the + :doc:`Namespaces chapter <namespaces>` in :ref:`namespace_self`). Since + ``index.html`` is the topmost template and also defines a block + called ``header``, it's this ``header`` block that ultimately gets + executed -- instead of the one that's present in ``base.html``. +#. Control comes back to ``base.html``. Some more HTML is + rendered. +#. ``base.html`` executes ``self.body()``. The ``body()`` + function on all template-based namespaces refers to the main + body of the template, therefore the main body of + ``index.html`` is rendered. +#. When ``<%block name="header">`` is encountered in ``index.html`` + during the ``self.body()`` call, a conditional is checked -- does the + current inherited template, i.e. ``base.html``, also define this block? If yes, + the ``<%block>`` is **not** executed here -- the inheritance + mechanism knows that the parent template is responsible for rendering + this block (and in fact it already has). In other words a block + only renders in its *basemost scope*. +#. Control comes back to ``base.html``. More HTML is rendered, + then the ``<%block name="footer">`` expression is invoked. +#. The ``footer`` block is only defined in ``base.html``, so being + the topmost definition of ``footer``, it's the one that + executes. If ``index.html`` also specified ``footer``, then + its version would **override** that of the base. +#. ``base.html`` finishes up rendering its HTML and the template + is complete, producing: + + .. sourcecode:: html <html> <body> @@ -317,8 +317,8 @@ in order to achieve this it *adds* the restriction that all block names in a sin to be globally unique within the template, and additionally that a ``<%block>`` can't be defined inside of a ``<%def>``. It's a more restricted tag suited towards a more specific use case than ``<%def>``. -Using the "next" namespace to produce content wrapping -======================================================= +Using the ``next`` namespace to produce content wrapping +========================================================= Sometimes you have an inheritance chain that spans more than two templates. Or maybe you don't, but you'd like to build your @@ -372,7 +372,6 @@ which inherits from ``base.html``: ${next.body()} </div> - And finally change ``index.html`` to inherit from ``layout.html`` instead: @@ -428,8 +427,8 @@ Without the ``next`` namespace, only the main body of .. _parent_namespace: -Using the "parent" namespace to augment defs -============================================= +Using the ``parent`` namespace to augment defs +=============================================== Lets now look at the other inheritance-specific namespace, the opposite of ``next`` called ``parent``. ``parent`` is the @@ -498,8 +497,8 @@ and you're now a template inheritance ninja! Inheritable Attributes ====================== -The ``attr`` accessor of the :class:`.Namespace` object allows access -to module level variables declared in a template. By accessing +The :attr:`attr <.Namespace.attr>` accessor of the :class:`.Namespace` object +allows access to module level variables declared in a template. By accessing ``self.attr``, you can access regular attributes from the inheritance chain as declared in ``<%! %>`` sections. Such as: @@ -514,7 +513,7 @@ inheritance chain as declared in ``<%! %>`` sections. Such as: </div> If an inheriting template overrides ``class_`` to be -``white``, as in: +``"white"``, as in: .. sourcecode:: mako @@ -532,3 +531,4 @@ you'll get output like: <div class="white"> This is the body </div> + diff --git a/doc/build/namespaces.rst b/doc/build/namespaces.rst index 96f05e3..070c9dd 100644 --- a/doc/build/namespaces.rst +++ b/doc/build/namespaces.rst @@ -38,7 +38,7 @@ current context. ``<%namespace>`` also provides an ``import`` attribute which can be used to pull the names into the local namespace, removing the -need to call it via the ".". When ``import`` is used, the +need to call it via the "``.``" operator. When ``import`` is used, the ``name`` attribute is optional. .. sourcecode:: mako @@ -48,7 +48,7 @@ need to call it via the ".". When ``import`` is used, the Heres comp1: ${comp1()} Heres comp2: ${comp2(x=5)} -``import`` also supports the "*" operator: +``import`` also supports the "``*``" operator: .. sourcecode:: mako @@ -206,8 +206,8 @@ pulled in from a remote template or module: .. _namespaces_body: -The "body()" method -===================== +The ``body()`` method +======================= Every namespace that is generated from a template contains a method called ``body()``. This method corresponds to the main @@ -271,8 +271,8 @@ two) for free. The names of these namespaces are ``local`` and .. _namespace_local: -local ------ +``local`` +--------- The ``local`` namespace is basically the namespace for the currently executing template. This means that all of the top @@ -286,8 +286,8 @@ can be particularly useful. .. _namespace_self: -self ------ +``self`` +--------- The ``self`` namespace, in the case of a template that does not use inheritance, is synonymous with ``local``. If inheritance is diff --git a/doc/build/runtime.rst b/doc/build/runtime.rst index d2c18bb..d42a922 100644 --- a/doc/build/runtime.rst +++ b/doc/build/runtime.rst @@ -75,7 +75,7 @@ automatically correspond to what was passed into the current the current context?** - The value you get back is a special value called ``UNDEFINED``, or if the ``strict_undefined=True`` flag is used a ``NameError`` is raised. ``UNDEFINED`` is just a simple global - variable with the class ``mako.runtime.Undefined``. The + variable with the class :class:`mako.runtime.Undefined`. The ``UNDEFINED`` object throws an error when you call ``str()`` on it, which is what happens if you try to use it in an expression. @@ -169,7 +169,7 @@ Significant members of :class:`.Context` include: the context if it isn't defined somewhere already. Use the dictionary accessor and/or ``get`` method when you want a variable that *is* already defined somewhere else, such as in - the local arguments sent to a %def call. If a key is not + the local arguments sent to a ``%def`` call. If a key is not present, like a dictionary it raises ``KeyError``. * ``keys()`` - all the names defined within this context. * ``kwargs`` - this returns a **copy** of the context's @@ -333,11 +333,15 @@ all templates, then re-enabled on a per-template basis for those templates which to make use of the new system. First, the ``enable_loop=False`` flag is passed to either the :class:`.TemplateLookup` -or :class:`.Template` object in use:: +or :class:`.Template` object in use: + +.. sourcecode:: python lookup = TemplateLookup(directories=['/docs'], enable_loop=False) -or:: +or: + +.. sourcecode:: python template = Template("some template", enable_loop=False) @@ -398,7 +402,7 @@ to the context and can't be substituted -- see the section :ref:`reserved_names` an instance of :class:`.Undefined`, and raises an exception when its ``__str__()`` method is called. * ``pageargs`` - this is a dictionary which is present in a - template which does not define any \**kwargs section in its + template which does not define any ``**kwargs`` section in its ``<%page>`` tag. All keyword arguments sent to the ``body()`` function of a template (when used via namespaces) go here by default unless otherwise defined as a page argument. If this @@ -420,7 +424,6 @@ ignored or lead to other error messages. * ``loop`` - see :ref:`loop_context`. Note this can be disabled for legacy templates via the ``enable_loop=False`` argument; see :ref:`migrating_loop`. - API Reference ============== diff --git a/doc/build/syntax.rst b/doc/build/syntax.rst index 3fa10ca..875085e 100644 --- a/doc/build/syntax.rst +++ b/doc/build/syntax.rst @@ -27,7 +27,7 @@ Perl, Genshi, JSP EL, and others: Above, the string representation of ``x`` is applied to the template's output stream. If you're wondering where ``x`` comes -from, it's usually from the ``Context`` supplied to the +from, it's usually from the :class:`.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. @@ -68,8 +68,8 @@ 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, +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 @@ -84,7 +84,7 @@ using another ``%`` marker with the tag "``end<name>``", where The ``%`` can appear anywhere on the line as long as no text precedes it; indentation is not significant. The full range of Python "colon" expressions are allowed here, including -``if/elif/else``, ``while``, ``for``, and even ``def``, although +``if``/``elif``/``else``, ``while``, ``for``, and even ``def``, although Mako has a built-in tag for defs which is more full-featured. .. sourcecode:: mako @@ -158,7 +158,9 @@ the next line: here is a line that goes onto \ another line. -The above text evaluates to:: +The above text evaluates to: + +.. sourcecode:: text here is a line that goes onto another line. @@ -247,8 +249,8 @@ valid. Heres a quick summary of all the tags: -<%page> -------- +``<%page>`` +----------- This tag defines general characteristics of the template, including caching arguments, and optional lists of arguments @@ -271,10 +273,10 @@ 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> ------------ +``<%include>`` +--------------- -A tag that is familiar from other template languages, %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: @@ -292,8 +294,8 @@ Include also accepts arguments which are available as ``<%page>`` arguments in t <%include file="toolbar.html" args="current_section='members', username='ed'"/> -<%def> ------- +``<%def>`` +---------- The ``%def`` tag defines a Python function which contains a set of content, that can be called at some other point in the @@ -307,17 +309,17 @@ template. The basic idea is simple: ${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 +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 +:class:`.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`. +full deal on what ``%def`` can do in :ref:`defs_toplevel`. -<%block> ---------- +``<%block>`` +------------- ``%block`` is a tag that's new as of Mako 0.4.1. It's close to a ``%def``, except executes itself immediately in its base-most scope, @@ -345,10 +347,10 @@ to do inheritance: Blocks are introduced in :ref:`blocks` and further described in :ref:`inheritance_toplevel`. -<%namespace> -------------- +``<%namespace>`` +----------------- -%namespace is Mako's equivalent of Python's ``import`` +``%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. @@ -357,15 +359,15 @@ as locally defined "packages" of functions. <%namespace file="functions.html" import="*"/> -The underlying object generated by %namespace, an instance of +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>`` +-------------- Inherit allows templates to arrange themselves in **inheritance chains**. This is a concept familiar in many other template @@ -375,15 +377,15 @@ languages. <%inherit file="base.html"/> -When using the %inherit tag, control is passed to the topmost +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 flexibility in this area, including dynamic inheritance, content wrapping, and polymorphic method calls. Check it out in :ref:`inheritance_toplevel`. -<%nsname:defname> -------------------------- +``<%``\ nsname\ ``:``\ 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 @@ -400,17 +402,17 @@ tag, respectively. To create custom tags which accept a body, see :ref:`defs_with_content`. -<%call> -------- +``<%call>`` +----------- The call tag is the "classic" form of a user-defined tag, and is roughly equivalent to the ``<%namespacename:defname>`` syntax described above. This tag is also described in :ref:`defs_with_content`. -<%doc> ------- +``<%doc>`` +---------- -The doc tag handles multiline comments: +The ``%doc`` tag handles multiline comments: .. sourcecode:: mako @@ -421,8 +423,8 @@ The doc tag handles multiline comments: Also the ``##`` symbol as the first non-space characters on a line can be used for single line comments. -<%text> -------- +``<%text>`` +----------- This tag suspends the Mako lexer's normal parsing of Mako template directives, and returns its entire body contents as diff --git a/doc/build/unicode.rst b/doc/build/unicode.rst index d0cda5d..e0537c8 100644 --- a/doc/build/unicode.rst +++ b/doc/build/unicode.rst @@ -60,7 +60,7 @@ the storage format for strings. The "pass through encoded data" scheme is what template languages like Cheetah and earlier versions of Myghty do by default. Mako as of version 0.2 also supports this mode of -operation when using Python 2, using the "disable_unicode=True" +operation when using Python 2, using the ``disable_unicode=True`` flag. However, when using Mako in its default mode of unicode-aware, it requires explicitness when dealing with non-ASCII encodings. Additionally, if you ever need to handle @@ -76,12 +76,15 @@ output streams are handled internally as Python ``unicode`` objects. It's only at the point of :meth:`~.Template.render` that this unicode stream may be rendered into whatever the desired output encoding is. The implication here is that the template developer must -ensure that the encoding of all non-ASCII templates is explicit -(still required in Python 3), that all non-ASCII-encoded -expressions are in one way or another converted to unicode (not -much of a burden in Python 3), and that the output stream of the +:ensure that :ref:`the encoding of all non-ASCII templates is explicit +<set_template_file_encoding>` (still required in Python 3), +that :ref:`all non-ASCII-encoded expressions are in one way or another +converted to unicode <handling_non_ascii_expressions>` +(not much of a burden in Python 3), and that :ref:`the output stream of the template is handled as a unicode stream being encoded to some -encoding (still required in Python 3). +encoding <defining_output_encoding>` (still required in Python 3). + +.. _set_template_file_encoding: Specifying the Encoding of a Template File =========================================== @@ -127,6 +130,8 @@ The above will assume all located templates specify ``utf-8`` encoding, unless the template itself contains its own magic encoding comment, which takes precedence. +.. _handling_non_ascii_expressions: + Handling Expressions ===================== @@ -202,6 +207,8 @@ The ``default_filters`` argument can be used to entirely customize the filtering process of expressions. This argument is described in :ref:`filtering_default_filters`. +.. _defining_output_encoding: + Defining Output Encoding ========================= @@ -209,7 +216,7 @@ Now that we have a template which produces a pure unicode output stream, all the hard work is done. We can take the output and do anything with it. -As stated in the "Usage" chapter, both :class:`.Template` and +As stated in the :doc:`"Usage" chapter <usage>`, 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: @@ -310,19 +317,20 @@ is a regular byte-string. When ``disable_unicode=True`` is turned on, the ``default_filters`` argument which normally defaults to ``["unicode"]`` now defaults -to ``["str"]`` instead. Setting default_filters to the empty list +to ``["str"]`` instead. Setting ``default_filters`` to the empty list ``[]`` can remove the overhead of the ``str`` call. Also, in this mode you **cannot** safely call :meth:`~.Template.render_unicode` -- you'll get unicode/decode errors. The ``h`` filter (HTML escape) uses a less performant pure Python escape function in non-unicode mode (note that in versions prior -to 0.3.4, it used cgi.escape(), which has been replaced with a +to 0.3.4, it used ``cgi.escape()``, which has been replaced with a function that also escapes single quotes). This because MarkupSafe only supports Python unicode objects for non-ASCII strings. -**Rules for using disable_unicode=True** +Rules for using ``disable_unicode=True`` +---------------------------------------- * Don't use this mode unless you really, really want to and you absolutely understand what you're doing. @@ -333,4 +341,3 @@ strings. * Python 3 is unicode by default, and the flag is not available when running on Python 3. - diff --git a/doc/build/usage.rst b/doc/build/usage.rst index b4c5fee..0e50ddf 100644 --- a/doc/build/usage.rst +++ b/doc/build/usage.rst @@ -13,7 +13,9 @@ of integrating Mako's API is already done for you, in which case 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:: +the :class:`.Template` class: + +.. sourcecode:: python from mako.template import Template @@ -32,7 +34,9 @@ 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:: +method: + +.. sourcecode:: python from mako.template import Template @@ -43,7 +47,9 @@ 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:: +render with it, using the :meth:`~.Template.render_context` method: + +.. sourcecode:: python from mako.template import Template from mako.runtime import Context @@ -59,7 +65,9 @@ Using File-Based Templates =========================== A :class:`.Template` can also load its template source code from a file, -using the ``filename`` keyword argument:: +using the ``filename`` keyword argument: + +.. sourcecode:: python from mako.template import Template @@ -68,9 +76,11 @@ using the ``filename`` keyword argument:: 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 +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:: +the template: + +.. sourcecode:: python from mako.template import Template @@ -85,8 +95,8 @@ automatically re-used. .. _usage_templatelookup: -Using TemplateLookup -==================== +Using ``TemplateLookup`` +======================== All of the examples thus far have dealt with the usage of a single :class:`.Template` object. If the code within those templates @@ -96,7 +106,9 @@ resolution of other templates from within a template 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 :class:`.Template` objects it creates:: +the :class:`.Template` objects it creates: + +.. sourcecode:: python from mako.template import Template from mako.lookup import TemplateLookup @@ -115,7 +127,9 @@ 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 :class:`.TemplateLookup`, using the aptly named :meth:`~.TemplateLookup.get_template` method, which accepts the URI of the -desired template:: +desired template: + +.. sourcecode:: python from mako.template import Template from mako.lookup import TemplateLookup @@ -150,7 +164,9 @@ 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 :class:`.TemplateLookup` size is unbounded. You can specify a fixed -size using the ``collection_size`` argument:: +size using the ``collection_size`` argument: + +.. sourcecode:: python mylookup = TemplateLookup(directories=['/docs'], module_directory='/tmp/mako_modules', collection_size=500) @@ -180,7 +196,9 @@ Using Unicode and Encoding 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:: +output in any Python supported codec: + +.. sourcecode:: python from mako.template import Template from mako.lookup import TemplateLookup @@ -196,12 +214,16 @@ object, **if** ``output_encoding`` is set. Otherwise it returns a 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``:: +Python 3 a ``string``: + +.. sourcecode:: python print mytemplate.render_unicode() The above method disregards the output encoding keyword -argument; you can encode yourself by saying:: +argument; you can encode yourself by saying: + +.. sourcecode:: python print mytemplate.render_unicode().encode('utf-8', 'replace') @@ -234,7 +256,9 @@ will be converted to be against the originating template file. 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:: +Usage of these handlers usually looks like: + +.. sourcecode:: python from mako import exceptions @@ -244,7 +268,9 @@ Usage of these handlers usually looks like:: except: print exceptions.text_error_template().render() -Or for the HTML render function:: +Or for the HTML render function: + +.. sourcecode:: python from mako import exceptions @@ -259,7 +285,9 @@ 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.:: +E.g.: + +.. sourcecode:: python print exceptions.html_error_template().render(full=False) @@ -267,7 +295,9 @@ The HTML render function is also available built-in to :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 -:func:`.html_error_template`:: +:func:`.html_error_template`: + +.. sourcecode:: python template = Template(filename="/foo/bar", format_exceptions=True) print template.render() @@ -280,13 +310,15 @@ 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 :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:: +which describes its general API: + +.. sourcecode:: python from mako.exceptions import RichTraceback @@ -326,18 +358,18 @@ Pygments A `Pygments <http://pygments.pocoo.org>`_-compatible syntax 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 +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 +Mako provides support for extracting `gettext` messages from templates via a `Babel`_ extractor -entry point under `mako.ext.babelplugin`. +entry point under ``mako.ext.babelplugin``. -Gettext messages are extracted from all Python code sections, +`Gettext` messages are extracted from all Python code sections, including those of control lines and expressions embedded in tags. @@ -345,7 +377,7 @@ in tags. comments <http://babel.edgewall.org/wiki/Documentation/messages.html#comments-tags-and-translator-comments-explanation>`_ may also be extracted from Mako templates when a comment tag is specified to `Babel`_ (such as with -the -c option). +the ``-c`` option). For example, a project ``"myproj"`` contains the following Mako template at ``myproj/myproj/templates/name.html``: @@ -362,7 +394,9 @@ 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``): + +.. sourcecode:: cfg # Extraction from Python source files @@ -378,11 +412,15 @@ parameter specifying the encoding of the templates (identical to :class:`.Template`/:class:`.TemplateLookup`'s ``input_encoding`` parameter). Invoking `Babel`_'s extractor at the -command line in the project's root directory:: +command line in the project's root directory: + +.. sourcecode:: sh myproj$ pybabel extract -F babel.cfg -c "TRANSLATORS:" . -will output a gettext catalog to stdout including the following:: +will output a `gettext` catalog to `stdout` including the following: + +.. sourcecode:: pot #. TRANSLATORS: This is a proper name. See the gettext #. manual, section Names. @@ -391,13 +429,13 @@ will output a gettext catalog to stdout including the following:: msgstr "" This is only a basic example: -`Babel`_ can be invoked from setup.py +`Babel`_ can be invoked from ``setup.py`` and its command line options specified in the accompanying -setup.cfg via `Babel Distutils/Setuptools +``setup.cfg`` via `Babel Distutils/Setuptools Integration <http://babel.edgewall.org/wiki/Documentation/setup.html>`_. -Comments must immediately precede a gettext message to be -extracted. In the following case the TRANSLATORS: comment would +Comments must immediately precede a `gettext` message to be +extracted. In the following case the ``TRANSLATORS:`` comment would not have been extracted: .. sourcecode:: mako @@ -463,7 +501,7 @@ API Reference 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). + template, if any for that traceline (else the fields are ``None``). .. py:attribute:: reverse_records diff --git a/mako/cache.py b/mako/cache.py index e858a19..c831080 100644 --- a/mako/cache.py +++ b/mako/cache.py @@ -141,7 +141,7 @@ class Cache(object): self.invalidate('render_body', __M_defname='render_body') def invalidate_def(self, name): - """Invalidate the cached content of a particular <%def> within this + """Invalidate the cached content of a particular ``<%def>`` within this template. """ @@ -149,7 +149,7 @@ class Cache(object): self.invalidate('render_%s' % name, __M_defname='render_%s' % name) def invalidate_closure(self, name): - """Invalidate a nested <%def> within this template. + """Invalidate a nested ``<%def>`` within this template. Caching of nested defs is a blunt tool as there is no management of scope -- nested defs that use cache tags @@ -184,8 +184,9 @@ class CacheImpl(object): self.cache = cache pass_context = False - """If True, the Context will be passed to get_or_create - as the name 'context'.""" + """If ``True``, the :class:`.Context` will be passed to + :meth:`get_or_create <.CacheImpl.get_or_create>` as the name ``'context'``. + """ def get_or_create(self, key, creation_function, **kw): """Retrieve a value from the cache, using the given creation function diff --git a/mako/exceptions.py b/mako/exceptions.py index 4ce7875..0276957 100644 --- a/mako/exceptions.py +++ b/mako/exceptions.py @@ -53,7 +53,7 @@ class TopLevelLookupException(TemplateLookupException): pass class RichTraceback(object): - """Pull the current exception from the sys traceback and extracts + """Pull the current exception from the ``sys`` traceback and extracts Mako-specific template information. See the usage examples in :ref:`handling_exceptions`. @@ -248,9 +248,9 @@ def html_error_template(): filenames, line numbers and code for that of the originating source template, as applicable. - The template's default 'encoding_errors' value is 'htmlentityreplace'. The - template has two options. With the full option disabled, only a section of - an HTML document is returned. With the css option disabled, the default + The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The + template has two options. With the ``full`` option disabled, only a section of + an HTML document is returned. With the ``css`` option disabled, the default stylesheet won't be included. """ diff --git a/mako/lookup.py b/mako/lookup.py index 8696260..514ad9d 100644 --- a/mako/lookup.py +++ b/mako/lookup.py @@ -32,7 +32,7 @@ class TemplateCollection(object): def has_template(self, uri): """Return ``True`` if this :class:`.TemplateLookup` is capable of returning a :class:`.Template` object for the - given URI. + given ``uri``. :param uri: String URI of the template to be resolved. @@ -45,35 +45,35 @@ class TemplateCollection(object): def get_template(self, uri, relativeto=None): """Return a :class:`.Template` object corresponding to the given - URI. + ``uri``. The default implementation raises :class:`.NotImplementedError`. Implementations should - raise :class:`.TemplateLookupException` if the given uri + raise :class:`.TemplateLookupException` if the given ``uri`` cannot be resolved. :param uri: String URI of the template to be resolved. - :param relativeto: if present, the given URI is assumed to + :param relativeto: if present, the given ``uri`` is assumed to be relative to this URI. """ raise NotImplementedError() def filename_to_uri(self, uri, filename): - """Convert the given filename to a URI relative to - this TemplateCollection.""" + """Convert the given ``filename`` to a URI relative to + this :class:`.TemplateCollection`.""" return uri def adjust_uri(self, uri, filename): - """Adjust the given uri based on the calling filename. + """Adjust the given ``uri`` based on the calling ``filename``. When this method is called from the runtime, the - 'filename' parameter is taken directly to the 'filename' + ``filename`` parameter is taken directly to the ``filename`` attribute of the calling template. Therefore a custom - TemplateCollection subclass can place any string - identifier desired in the "filename" parameter of the - Template objects it constructs and have them come back + :class:`.TemplateCollection` subclass can place any string + identifier desired in the ``filename`` parameter of the + :class:`.Template` objects it constructs and have them come back here. """ @@ -84,13 +84,17 @@ class TemplateLookup(TemplateCollection): from the local filesystem. The primary argument is the ``directories`` argument, the list of - directories to search:: + directories to search: + + .. sourcecode:: python lookup = TemplateLookup(["/path/to/templates"]) some_template = lookup.get_template("/index.html") The :class:`.TemplateLookup` can also be given :class:`.Template` objects - programatically using :meth:`.put_string` or :meth:`.put_template`:: + programatically using :meth:`.put_string` or :meth:`.put_template`: + + .. sourcecode:: python lookup = TemplateLookup() lookup.put_string("base.html", ''' @@ -108,7 +112,7 @@ class TemplateLookup(TemplateCollection): to each directory and the filesystem checked. :param collection_size: Approximate size of the collection used - to store templates. If left at its default of -1, the size + to store templates. If left at its default of ``-1``, the size is unbounded, and a plain Python dictionary is used to relate URI strings to :class:`.Template` instances. Otherwise, a least-recently-used cache object is used which @@ -217,9 +221,9 @@ class TemplateLookup(TemplateCollection): def get_template(self, uri): """Return a :class:`.Template` object corresponding to the given - URI. + ``uri``. - Note the "relativeto" argument is not supported here at the moment. + .. note:: The ``relativeto`` argument is not supported here at the moment. """ @@ -239,7 +243,7 @@ class TemplateLookup(TemplateCollection): "Cant locate template for uri %r" % uri) def adjust_uri(self, uri, relativeto): - """Adjust the given uri based on the given relative URI.""" + """Adjust the given ``uri`` based on the given relative URI.""" key = (uri, relativeto) if key in self._uri_cache: @@ -257,8 +261,8 @@ class TemplateLookup(TemplateCollection): def filename_to_uri(self, filename): - """Convert the given filename to a URI relative to - this TemplateCollection.""" + """Convert the given ``filename`` to a URI relative to + this :class:`.TemplateCollection`.""" try: return self._uri_cache[filename] @@ -331,7 +335,7 @@ class TemplateLookup(TemplateCollection): def put_string(self, uri, text): """Place a new :class:`.Template` object into this :class:`.TemplateLookup`, based on the given string of - text. + ``text``. """ self._collection[uri] = Template( diff --git a/mako/runtime.py b/mako/runtime.py index acdc14a..640bc89 100644 --- a/mako/runtime.py +++ b/mako/runtime.py @@ -62,14 +62,14 @@ class Context(object): return self._kwargs.copy() def push_caller(self, caller): - """Push a 'caller' callable onto the callstack for + """Push a ``caller`` callable onto the callstack for this :class:`.Context`.""" self.caller_stack.append(caller) def pop_caller(self): - """Pop a 'caller' callable onto the callstack for this + """Pop a ``caller`` callable onto the callstack for this :class:`.Context`.""" del self.caller_stack[-1] @@ -243,20 +243,20 @@ class LoopContext(object): See the section :ref:`loop_context` for usage notes. - :attr:`parent` -> LoopContext or None + :attr:`parent` -> :class:`.LoopContext` or ``None`` The parent loop, if one exists. - :attr:`index` -> int + :attr:`index` -> `int` The 0-based iteration count. - :attr:`reverse_index` -> int + :attr:`reverse_index` -> `int` The number of iterations remaining. - :attr:`first` -> bool - `True` on the first iteration, `False` otherwise. - :attr:`last` -> bool - `True` on the last iteration, `False` otherwise. - :attr:`even` -> bool - `True` when `index` is even. - :attr:`odd` -> bool - `True` when `index` is odd. + :attr:`first` -> `bool` + ``True`` on the first iteration, ``False`` otherwise. + :attr:`last` -> `bool` + ``True`` on the last iteration, ``False`` otherwise. + :attr:`even` -> `bool` + ``True`` when ``index`` is even. + :attr:`odd` -> `bool` + ``True`` when ``index`` is odd. """ def __init__(self, iterable): @@ -318,7 +318,9 @@ class Namespace(object): can be local, from other templates, or from imported modules. To access a particular rendering method referenced by a - :class:`.Namespace`, use plain attribute access:: + :class:`.Namespace`, use plain attribute access: + + .. sourcecode:: mako ${some_namespace.foo(x, y, z)} @@ -339,7 +341,7 @@ class Namespace(object): callables = () module = None - """The Python module referenced by this Namespace. + """The Python module referenced by this :class:`.Namespace`. If the namespace references a :class:`.Template`, then this module is the equivalent of ``template.module``, @@ -354,7 +356,7 @@ class Namespace(object): """ context = None - """The :class:`.Context` object for this namespace. + """The :class:`.Context` object for this :class:`.Namespace`. Namespaces are often created with copies of contexts that contain slightly different data, particularly in inheritance @@ -366,17 +368,17 @@ class Namespace(object): filename = None """The path of the filesystem file used for this - Namespace's module or template. + :class:`.Namespace`'s module or template. If this is a pure module-based - Namespace, this evaluates to ``module.__file__``. If a + :class:`.Namespace`, this evaluates to ``module.__file__``. If a template-based namespace, it evaluates to the original template file location. """ uri = None - """The URI for this Namespace's template. + """The URI for this :class:`.Namespace`'s template. I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`. @@ -399,11 +401,11 @@ class Namespace(object): return _NSAttr(self) def get_namespace(self, uri): - """Return a :class:`.Namespace` corresponding to the given uri. + """Return a :class:`.Namespace` corresponding to the given ``uri``. - If the given uri is a relative URI (i.e. it does not - contain a leading slash ``/``), the uri is adjusted to - be relative to the uri of the namespace itself. This + If the given ``uri`` is a relative URI (i.e. it does not + contain a leading slash ``/``), the ``uri`` is adjusted to + be relative to the ``uri`` of the namespace itself. This method is therefore mostly useful off of the built-in ``local`` namespace, described in :ref:`namespace_local`. @@ -429,9 +431,9 @@ class Namespace(object): return ns def get_template(self, uri): - """Return a :class:`.Template` from the given uri. + """Return a :class:`.Template` from the given ``uri``. - The uri resolution is relative to the uri of this :class:`.Namespace` + The ``uri`` resolution is relative to the ``uri`` of this :class:`.Namespace` object's :class:`.Template`. """ @@ -461,7 +463,7 @@ class Namespace(object): return self.template.cache def include_file(self, uri, **kwargs): - """Include a file at the given uri.""" + """Include a file at the given ``uri``.""" _include_file(self.context, uri, self._templateuri, **kwargs) @@ -519,7 +521,7 @@ class TemplateNamespace(Namespace): @property def module(self): - """The Python module referenced by this Namespace. + """The Python module referenced by this :class:`.Namespace`. If the namespace references a :class:`.Template`, then this module is the equivalent of ``template.module``, @@ -531,13 +533,13 @@ class TemplateNamespace(Namespace): @property def filename(self): """The path of the filesystem file used for this - Namespace's module or template. + :class:`.Namespace`'s module or template. """ return self.template.filename @property def uri(self): - """The URI for this Namespace's template. + """The URI for this :class:`.Namespace`'s template. I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`. @@ -592,7 +594,7 @@ class ModuleNamespace(Namespace): @property def filename(self): """The path of the filesystem file used for this - Namespace's module or template. + :class:`.Namespace`'s module or template. """ return self.module.__file__ diff --git a/mako/template.py b/mako/template.py index e43aed3..9d77f3b 100644 --- a/mako/template.py +++ b/mako/template.py @@ -16,9 +16,9 @@ class Template(object): """Represents a compiled template. :class:`.Template` includes a reference to the original - template source (via the ``.source`` attribute) + template source (via the :attr:`.source` attribute) as well as the source code of the - generated Python module (i.e. the ``.code`` attribute), + generated Python module (i.e. the :attr:`.code` attribute), as well as a reference to an actual Python module. :class:`.Template` is constructed using either a literal string @@ -26,45 +26,45 @@ class Template(object): path to a source file. :param text: textual template source. This argument is mutually - exclusive versus the "filename" parameter. + exclusive versus the ``filename`` parameter. :param filename: filename of the source template. This argument is - mutually exclusive versus the "text" parameter. + mutually exclusive versus the ``text`` parameter. :param buffer_filters: string list of filters to be applied - to the output of %defs which are buffered, cached, or otherwise + to the output of ``%def``\ s which are buffered, cached, or otherwise filtered, after all filters - defined with the %def itself have been applied. Allows the + defined with the ``%def`` itself have been applied. Allows the creation of default expression filters that let the output - of return-valued %defs "opt out" of that filtering via + of return-valued ``%def``\ s "opt out" of that filtering via passing special attributes or objects. - :param bytestring_passthrough: When True, and output_encoding is - set to None, and :meth:`.Template.render` is used to render, - the StringIO or cStringIO buffer will be used instead of the + :param bytestring_passthrough: When ``True``, and ``output_encoding`` is + set to ``None``, and :meth:`.Template.render` is used to render, + the `StringIO` or `cStringIO` buffer will be used instead of the default "fast" buffer. This allows raw bytestrings in the output stream, such as in expressions, to pass straight through to the buffer. New in 0.4 to provide the same behavior as that of the previous series. This flag is forced - to True if disable_unicode is also configured. + to ``True`` if ``disable_unicode`` is also configured. :param cache_args: Dictionary of cache configuration arguments that will be passed to the :class:`.CacheImpl`. See :ref:`caching_toplevel`. - :param cache_dir: Deprecated; use the 'dir' argument in the - cache_args dictionary. See :ref:`caching_toplevel`. + :param cache_dir: Deprecated; use the ``'dir'`` argument in the + ``cache_args`` dictionary. See :ref:`caching_toplevel`. :param cache_enabled: Boolean flag which enables caching of this template. See :ref:`caching_toplevel`. :param cache_impl: String name of a :class:`.CacheImpl` caching - implementation to use. Defaults to 'beaker'. + implementation to use. Defaults to ``'beaker'``. - :param cache_type: Deprecated; use the 'type' argument in the - cache_args dictionary. See :ref:`caching_toplevel`. + :param cache_type: Deprecated; use the ``'type'`` argument in the + ``cache_args`` dictionary. See :ref:`caching_toplevel`. - :param cache_url: Deprecated; use the 'url' argument in the - cache_args dictionary. See :ref:`caching_toplevel`. + :param cache_url: Deprecated; use the ``'url'`` argument in the + ``cache_args`` dictionary. See :ref:`caching_toplevel`. :param default_filters: List of string filter names that will be applied to all expressions. See :ref:`filtering_default_filters`. @@ -74,7 +74,7 @@ class Template(object): :param enable_loop: When ``True``, enable the ``loop`` context variable. This can be set to ``False`` to support templates that may - be making usage of the name "loop". Individual templates can + be making usage of the name "``loop``". Individual templates can re-enable the "loop" context by placing the directive ``enable_loop="True"`` inside the ``<%page>`` tag -- see :ref:`migrating_loop`. @@ -123,28 +123,30 @@ class Template(object): path to be written to. The default behavior of module writing uses a tempfile in conjunction with a file move in order to make the operation atomic. So a user-defined module - writing function that mimics the default behavior would be:: + writing function that mimics the default behavior would be: - import tempfile - import os - import shutil + .. sourcecode:: python - def module_writer(source, outputpath): - (dest, name) = \\ - tempfile.mkstemp( - dir=os.path.dirname(outputpath) - ) + import tempfile + import os + import shutil - os.write(dest, source) - os.close(dest) - shutil.move(name, outputpath) + def module_writer(source, outputpath): + (dest, name) = \\ + tempfile.mkstemp( + dir=os.path.dirname(outputpath) + ) - from mako.template import Template - mytemplate = Template( - file="index.html", - module_directory="/path/to/modules", - module_writer=module_writer - ) + os.write(dest, source) + os.close(dest) + shutil.move(name, outputpath) + + from mako.template import Template + mytemplate = Template( + file="index.html", + module_directory="/path/to/modules", + module_writer=module_writer + ) The function is provided for unusual configurations where certain platform-specific permissions or other special @@ -166,9 +168,9 @@ class Template(object): missing variables which include the name. New in 0.3.6. :param uri: string URI or other identifier for this template. - If not provided, the uri is generated from the filesystem + 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 provide a key + template. The primary usage of the ``uri`` is to provide a key within :class:`.TemplateLookup`, as well as to generate the file path of the generated Python module file, if ``module_directory`` is specified. @@ -358,13 +360,13 @@ class Template(object): @property def source(self): - """Return the template source code for this Template.""" + """Return the template source code for this :class:`.Template`.""" return _get_module_info_from_callable(self.callable_).source @property def code(self): - """Return the module source code for this Template.""" + """Return the module source code for this :class:`.Template`.""" return _get_module_info_from_callable(self.callable_).code @@ -387,11 +389,11 @@ class Template(object): If the template specifies an output encoding, the string will be encoded accordingly, else the output is raw (raw - output uses cStringIO and can't handle multibyte - characters). A Context object is created corresponding + output uses `cStringIO` and can't handle multibyte + characters). A :class:`.Context` object is created corresponding to the given data. Arguments that are explicitly declared by this template's internal rendering method are also - pulled from the given \*args, \**data members. + pulled from the given ``*args``, ``**data`` members. """ return runtime._render(self, self.callable_, args, data) @@ -406,7 +408,7 @@ class Template(object): as_unicode=True) def render_context(self, context, *args, **kwargs): - """Render this Template with the given context. + """Render this :class:`.Template` with the given context. The data is written to the context's buffer. @@ -508,7 +510,7 @@ class ModuleTemplate(Template): ) class DefTemplate(Template): - """A Template which represents a callable def in a parent + """A :class:`.Template` which represents a callable def in a parent template.""" def __init__(self, parent, callable_): |