Mako-1.0.3/0000755000076500000240000000000012613724373013156 5ustar classicstaff00000000000000Mako-1.0.3/CHANGES0000644000076500000240000000026312613724132014143 0ustar classicstaff00000000000000===== MOVED ===== Please see: /docs/changelog.html /docs/build/changelog.rst or https://docs.makotemplates.org/en/latest/changelog.html for the current CHANGES. Mako-1.0.3/doc/0000755000076500000240000000000012613724373013723 5ustar classicstaff00000000000000Mako-1.0.3/doc/_sources/0000755000076500000240000000000012613724373015545 5ustar classicstaff00000000000000Mako-1.0.3/doc/_sources/caching.txt0000644000076500000240000003254712613724132017706 0ustar classicstaff00000000000000.. _caching_toplevel: ======= Caching ======= Any template or component can be cached using the ``cache`` argument to the ``<%page>``, ``<%def>`` or ``<%block>`` directives: .. sourcecode:: mako <%page cached="True"/> template text The above template, after being executed the first time, will store its content within a cache that by default is scoped within memory. Subsequent calls to the template's :meth:`~.Template.render` method will return content directly from the cache. When the :class:`.Template` object itself falls out of scope, its corresponding cache is garbage collected along with the template. The caching system requires that a cache backend be installed; this includes either the `Beaker `_ package or the `dogpile.cache `_, as well as any other third-party caching libraries that feature Mako integration. By default, caching will attempt to make use of Beaker. To use dogpile.cache, the ``cache_impl`` argument must be set; see this argument in the section :ref:`cache_arguments`. In addition to being available on the ``<%page>`` tag, the caching flag and all its options can be used with the ``<%def>`` tag as well: .. sourcecode:: mako <%def name="mycomp" cached="True" cache_timeout="60"> other text ... and equivalently with the ``<%block>`` tag, anonymous or named: .. sourcecode:: mako <%block cached="True" cache_timeout="60"> other text .. _cache_arguments: Cache Arguments =============== Mako has two cache arguments available on tags that are available in all cases. The rest of the arguments available are specific to a backend. The two generic tags arguments are: * ``cached="True"`` - enable caching for this ``<%page>``, ``<%def>``, or ``<%block>``. * ``cache_key`` - the "key" used to uniquely identify this content in the cache. Usually, this key is chosen automatically based on the name of the rendering callable (i.e. ``body`` when used in ``<%page>``, the name of the def when using ``<%def>``, the explicit or internally-generated name when using ``<%block>``). Using the ``cache_key`` parameter, the key can be overridden using a fixed or programmatically generated value. For example, here's a page that caches any page which inherits from it, based on the filename of the calling template: .. sourcecode:: mako <%page cached="True" cache_key="${self.filename}"/> ${next.body()} ## rest of template On a :class:`.Template` or :class:`.TemplateLookup`, the 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.: .. 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'``, indicating that the 'beaker' backend will be used. * ``cache_args`` - A dictionary of cache parameters that will be consumed by the cache backend. See :ref:`beaker_backend` and :ref:`dogpile.cache_backend` for examples. Backend-Specific Cache Arguments -------------------------------- The ``<%page>``, ``<%def>``, and ``<%block>`` tags accept any named argument that starts with the prefix ``"cache_"``. Those arguments are then packaged up and passed along to the underlying caching implementation, minus the ``"cache_"`` prefix. The actual arguments understood are determined by the backend. * :ref:`beaker_backend` - Includes arguments understood by Beaker. * :ref:`dogpile.cache_backend` - Includes arguments understood by dogpile.cache. .. _beaker_backend: Using the Beaker Cache Backend ------------------------------ When using Beaker, new implementations will want to make usage of **cache regions** so that cache configurations can be maintained externally to templates. These configurations live under named "regions" that can be referred to within templates themselves. .. versionadded:: 0.6.0 Support for Beaker cache regions. For example, suppose we would like two regions. One is a "short term" 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`: .. sourcecode:: python from beaker.cache import CacheManager manager = CacheManager(cache_regions={ 'short_term':{ 'type': 'memory', 'expire': 60 }, 'long_term':{ 'type': 'ext:memcached', 'url': '127.0.0.1:11211', 'expire': 300 } }) lookup = TemplateLookup( directories=['/path/to/templates'], module_directory='/path/to/modules', cache_impl='beaker', cache_args={ 'manager':manager } ) Our templates can then opt to cache data in one of either region, using the ``cache_region`` argument. Such as using ``short_term`` at the ``<%page>`` level: .. sourcecode:: mako <%page cached="True" cache_region="short_term"> ## ... Or, ``long_term`` at the ``<%block>`` level: .. sourcecode:: mako <%block name="header" cached="True" cache_region="long_term"> other text The Beaker backend also works without regions. There are a variety of arguments that can be passed to the ``cache_args`` dictionary, which are also allowable in templates via the ``<%page>``, ``<%block>``, and ``<%def>`` tags specific to those sections. The values given override those specified at the :class:`.TemplateLookup` or :class:`.Template` level. With the possible exception of ``cache_timeout``, these arguments are probably better off staying at the template configuration level. Each argument specified as ``cache_XYZ`` in a template tag is specified without the ``cache_`` prefix in the ``cache_args`` dictionary: * ``cache_timeout`` - number of seconds in which to invalidate the cached data. After this timeout, the content is re-generated on the next call. Available as ``timeout`` in the ``cache_args`` dictionary. * ``cache_type`` - type of caching. ``'memory'``, ``'file'``, ``'dbm'``, or ``'ext:memcached'`` (note that the string ``memcached`` is also accepted by the dogpile.cache Mako plugin, though not by Beaker itself). Available as ``type`` in the ``cache_args`` dictionary. * ``cache_url`` - (only used for ``memcached`` but required) a single IP address or a semi-colon separated list of IP address of memcache servers to use. Available as ``url`` in the ``cache_args`` dictionary. * ``cache_dir`` - in the case of the ``'file'`` and ``'dbm'`` cache types, this is the filesystem directory with which to store data files. If this option is not present, the value of ``module_directory`` is used (i.e. the directory where compiled template modules are stored). If neither option is available an exception is thrown. Available as ``dir`` in the ``cache_args`` dictionary. .. _dogpile.cache_backend: Using the dogpile.cache Backend ------------------------------- `dogpile.cache`_ is a new replacement for Beaker. It provides a modernized, slimmed down interface and is generally easier to use than Beaker. As of this writing it has not yet been released. dogpile.cache includes its own Mako cache plugin -- see :mod:`dogpile.cache.plugins.mako_cache` in the dogpile.cache documentation. Programmatic Cache Access ========================= The :class:`.Template`, as well as any template-derived :class:`.Namespace`, has 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 values: .. sourcecode:: mako <% local.cache.set("somekey", type="memory", "somevalue") %> Above, the cache associated with the ``local`` namespace is accessed and a key is placed within a memory cache. More commonly, the ``cache`` object is used to invalidate cached sections programmatically: .. sourcecode:: python template = lookup.get_template('/sometemplate.html') # invalidate the "body" of the template template.cache.invalidate_body() # invalidate an individual def template.cache.invalidate_def('somedef') # invalidate an arbitrary key template.cache.invalidate('somekey') You can access any special method or attribute of the :class:`.CacheImpl` itself using the :attr:`impl <.Cache.impl>` attribute: .. sourcecode:: python template.cache.impl.do_something_special() Note that using implementation-specific methods will mean you can't swap in a different kind of :class:`.CacheImpl` implementation at a later time. .. _cache_plugins: Cache Plugins ============= The mechanism used by caching can be plugged in using a :class:`.CacheImpl` subclass. This class implements the rudimental methods Mako needs to implement the caching API. Mako includes the :class:`.BeakerCacheImpl` class to 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 at runtime via a convenience installer :func:`.register_plugin` which accomplishes essentially the same task. An example plugin that implements a local dictionary cache: .. sourcecode:: python from mako.cache import Cacheimpl, register_plugin class SimpleCacheImpl(CacheImpl): def __init__(self, cache): super(SimpleCacheImpl, self).__init__(cache) self._cache = {} def get_or_create(self, key, creation_function, **kw): if key in self._cache: return self._cache[key] else: self._cache[key] = value = creation_function() return value def set(self, key, value, **kwargs): self._cache[key] = value def get(self, key, **kwargs): return self._cache.get(key) def invalidate(self, key, **kwargs): self._cache.pop(key, None) # optional - register the class locally register_plugin("simple", __name__, "SimpleCacheImpl") Enabling the above plugin in a template would look like: .. sourcecode:: python t = Template("mytemplate", file="mytemplate.html", cache_impl='simple') Guidelines for Writing Cache Plugins ------------------------------------ * The :class:`.CacheImpl` is created on a per-:class:`.Template` basis. The class should ensure that only data for the parent :class:`.Template` is persisted or returned by the cache methods. The actual :class:`.Template` is available via the ``self.cache.template`` attribute. The ``self.cache.id`` attribute, which is essentially the unique modulename of the template, is a good value to use in order to represent a unique namespace of keys specific to the template. * Templates only use the :meth:`.CacheImpl.get_or_create()` method in an implicit fashion. The :meth:`.CacheImpl.set`, :meth:`.CacheImpl.get`, and :meth:`.CacheImpl.invalidate` methods are only used in response to direct programmatic access to the corresponding methods on the :class:`.Cache` object. * :class:`.CacheImpl` will be accessed in a multithreaded fashion if the :class:`.Template` itself is used multithreaded. Care should be taken to ensure caching implementations are threadsafe. * A library like `Dogpile `_, which is a minimal locking system derived from Beaker, can be used to help implement the :meth:`.CacheImpl.get_or_create` method in a threadsafe way that can maximize effectiveness across multiple threads as well as processes. :meth:`.CacheImpl.get_or_create` is the key method used by templates. * All arguments passed to ``**kw`` come directly from the parameters inside the ``<%def>``, ``<%block>``, or ``<%page>`` tags directly, minus the ``"cache_"`` prefix, as strings, with the exception of the argument ``cache_timeout``, which is passed to the plugin as the name ``timeout`` with the value converted to an integer. Arguments present in ``cache_args`` on :class:`.Template` or :class:`.TemplateLookup` are passed directly, but are superseded by those present in the most specific template tag. * The directory where :class:`.Template` places module files can be acquired using the accessor ``self.cache.template.module_directory``. This directory can be a good place to throw cache-related work files, underneath a prefix like ``_my_cache_work`` so that name conflicts with generated modules don't occur. API Reference ============= .. autoclass:: mako.cache.Cache :members: :show-inheritance: .. autoclass:: mako.cache.CacheImpl :members: :show-inheritance: .. autofunction:: mako.cache.register_plugin .. autoclass:: mako.ext.beaker_cache.BeakerCacheImpl :members: :show-inheritance: Mako-1.0.3/doc/_sources/changelog.txt0000644000076500000240000015162312613724176020246 0ustar classicstaff00000000000000========= Changelog ========= 1.0 === .. changelog:: :version: 1.0.3 :released: Tue Oct 27 2015 .. change:: :tags: bug, babel :pullreq: bitbucket:21 Fixed an issue where the Babel plugin would not handle a translation symbol that contained non-ascii characters. Pull request courtesy Roman Imankulov. .. changelog:: :version: 1.0.2 :released: Wed Aug 26 2015 .. change:: :tags: bug, installation :tickets: 249 The "universal wheel" marker is removed from setup.cfg, because our setup.py currently makes use of conditional dependencies. In :ticket:`249`, the discussion is ongoing on how to correct our setup.cfg / setup.py fully so that we can handle the per-version dependency changes while still maintaining optimal wheel settings, so this issue is not yet fully resolved. .. change:: :tags: bug, py3k :tickets: 250 Repair some calls within the ast module that no longer work on Python3.5; additionally replace the use of ``inspect.getargspec()`` under Python 3 (seems to be called from the TG plugin) to avoid deprecation warnings. .. change:: :tags: bug :pullreq: bitbucket:18 Update the Lingua translation extraction plugin to correctly handle templates mixing Python control statements (such as if, for and while) with template fragments. Pull request courtesy Laurent Daverio. .. change:: :tags: feature :tickets: 236 Added ``STOP_RENDERING`` keyword for returning/exiting from a template early, which is a synonym for an empty string ``""``. Previously, the docs suggested a bare ``return``, but this could cause ``None`` to appear in the rendered template result. .. seealso:: :ref:`syntax_exiting_early` .. changelog:: :version: 1.0.1 :released: Thu Jan 22 2015 .. change:: :tags: feature :pullreq: bitbucket:9 Added support for Lingua, a translation extraction system as an alternative to Babel. Pull request courtesy Wichert Akkerman. .. change:: :tags: bug, py3k :pullreq: bitbucket:11 Modernized the examples/wsgi/run_wsgi.py file for Py3k. Pull requset courtesy Cody Taylor. .. changelog:: :version: 1.0.0 :released: Sun Jun 8 2014 .. change:: :tags: bug, py2k :pullreq: bitbucket:8 Improved the error re-raise operation when a custom :paramref:`.Template.error_handler` is used that does not handle the exception; the original stack trace etc. is now preserved. Pull request courtesy Manfred Haltner. .. change:: :tags: bug, py2k, filters :pullreq: bitbucket:7 Added an html_escape filter that works in "non unicode" mode. Previously, when using ``disable_unicode=True``, the ``u`` filter would fail to handle non-ASCII bytes properly. Pull request courtesy George Xie. .. change:: :tags: general Compatibility changes; in order to modernize the codebase, Mako is now dropping support for Python 2.4 and Python 2.5 altogether. The source base is now targeted at Python 2.6 and forwards. .. change:: :tags: feature Template modules now generate a JSON "metadata" structure at the bottom of the source file which includes parseable information about the templates' source file, encoding etc. as well as a mapping of module source lines to template lines, thus replacing the "# SOURCE LINE" markers throughout the source code. The structure also indicates those lines that are explicitly not part of the template's source; the goal here is to allow better integration with coverage and other tools. .. change:: :tags: bug, py3k Fixed bug in ``decode.`` filter where a non-string object would not be correctly interpreted in Python 3. .. change:: :tags: bug, py3k :tickets: 227 Fixed bug in Python parsing logic which would fail on Python 3 when a "try/except" targeted a tuple of exception types, rather than a single exception. .. change:: :tags: feature :pullreq: bitbucket:5 mako-render is now implemented as a setuptools entrypoint script; a standalone mako.cmd.cmdline() callable is now available, and the system also uses argparse now instead of optparse. Pull request courtesy Derek Harland. .. change:: :tags: feature :pullreq: bitbucket:4 The mako-render script will now catch exceptions and run them into the text error handler, and exit with a non-zero exit code. Pull request courtesy Derek Harland. .. change:: :tags: bug :pullreq: bitbucket:2 A rework of the mako-render script allows the script to run correctly when given a file pathname that is outside of the current directory, e.g. ``mako-render ../some_template.mako``. In this case, the "template root" defaults to the directory in which the template is located, instead of ".". The script also accepts a new argument ``--template-dir`` which can be specified multiple times to establish template lookup directories. Standard input for templates also works now too. Pull request courtesy Derek Harland. .. change:: :tags: feature, py3k :pullreq: github:7 Support is added for Python 3 "keyword only" arguments, as used in defs. Pull request courtesy Eevee. 0.9 === .. changelog:: :version: 0.9.1 :released: Thu Dec 26 2013 .. change:: :tags: bug :tickets: 225 Fixed bug in Babel plugin where translator comments would be lost if intervening text nodes were encountered. Fix courtesy Ned Batchelder. .. change:: :tags: bug :tickets: Fixed TGPlugin.render method to support unicode template names in Py2K - courtesy Vladimir Magamedov. .. change:: :tags: bug :tickets: Fixed an AST issue that was preventing correct operation under alpha versions of Python 3.4. Pullreq courtesy Zer0-. .. change:: :tags: bug :tickets: Changed the format of the "source encoding" header output by the code generator to use the format ``# -*- coding:%s -*-`` instead of ``# -*- encoding:%s -*-``; the former is more common and compatible with emacs. Courtesy Martin Geisler. .. change:: :tags: bug :tickets: 224 Fixed issue where an old lexer rule prevented a template line which looked like "#*" from being correctly parsed. .. changelog:: :version: 0.9.0 :released: Tue Aug 27 2013 .. change:: :tags: bug :tickets: 219 The Context.locals_() method becomes a private underscored method, as this method has a specific internal use. The purpose of Context.kwargs has been clarified, in that it only delivers top level keyword arguments originally passed to template.render(). .. change:: :tags: bug :tickets: Fixed the babel plugin to properly interpret ${} sections inside of a "call" tag, i.e. <%self:some_tag attr="${_('foo')}"/>. Code that's subject to babel escapes in here needs to be specified as a Python expression, not a literal. This change is backwards incompatible vs. code that is relying upon a _('') translation to be working within a call tag. .. change:: :tags: bug :tickets: 187 The Babel plugin has been repaired to work on Python 3. .. change:: :tags: bug :tickets: 207 Using <%namespace import="*" module="somemodule"/> now skips over module elements that are not explcitly callable, avoiding TypeError when trying to produce partials. .. change:: :tags: bug :tickets: 190 Fixed Py3K bug where a "lambda" expression was not interpreted correctly within a template tag; also fixed in Py2.4. 0.8 === .. changelog:: :version: 0.8.1 :released: Fri May 24 2013 .. change:: :tags: bug :tickets: 216 Changed setup.py to skip installing markupsafe if Python version is < 2.6 or is between 3.0 and less than 3.3, as Markupsafe now only supports 2.6->2.X, 3.3->3.X. .. change:: :tags: bug :tickets: 214 Fixed regression where "entity" filter wasn't converted for py3k properly (added tests.) .. change:: :tags: bug :tickets: 212 Fixed bug where mako-render script wasn't compatible with Py3k. .. change:: :tags: bug :tickets: 213 Cleaned up all the various deprecation/ file warnings when running the tests under various Pythons with warnings turned on. .. changelog:: :version: 0.8.0 :released: Wed Apr 10 2013 .. change:: :tags: feature :tickets: Performance improvement to the "legacy" HTML escape feature, used for XML escaping and when markupsafe isn't present, courtesy George Xie. .. change:: :tags: bug :tickets: 209 Fixed bug whereby an exception in Python 3 against a module compiled to the filesystem would fail trying to produce a RichTraceback due to the content being in bytes. .. change:: :tags: bug :tickets: 208 Change default for compile()->reserved_names from tuple to frozenset, as this is expected to be a set by default. .. change:: :tags: feature :tickets: Code has been reworked to support Python 2.4-> Python 3.xx in place. 2to3 no longer needed. .. change:: :tags: feature :tickets: Added lexer_cls argument to Template, TemplateLookup, allows alternate Lexer classes to be used. .. change:: :tags: feature :tickets: Added future_imports parameter to Template and TemplateLookup, renders the __future__ header with desired capabilities at the top of the generated template module. Courtesy Ben Trofatter. 0.7 === .. changelog:: :version: 0.7.3 :released: Wed Nov 7 2012 .. change:: :tags: bug :tickets: legacy_html_escape function, used when Markupsafe isn't installed, was using an inline-compiled regexp which causes major slowdowns on Python 3.3; is now precompiled. .. change:: :tags: bug :tickets: 201 AST supporting now supports tuple-packed function arguments inside pure-python def or lambda expressions. .. change:: :tags: bug :tickets: Fixed Py3K bug in the Babel extension. .. change:: :tags: bug :tickets: Fixed the "filter" attribute of the <%text> tag so that it pulls locally specified identifiers from the context the same way as that of <%block> and <%filter>. .. change:: :tags: bug :tickets: Fixed bug in plugin loader to correctly raise exception when non-existent plugin is specified. .. changelog:: :version: 0.7.2 :released: Fri Jul 20 2012 .. change:: :tags: bug :tickets: 193 Fixed regression in 0.7.1 where AST parsing for Py2.4 was broken. .. changelog:: :version: 0.7.1 :released: Sun Jul 8 2012 .. change:: :tags: feature :tickets: 146 Control lines with no bodies will now succeed, as "pass" is added for these when no statements are otherwise present. Courtesy Ben Trofatter .. change:: :tags: bug :tickets: 192 Fixed some long-broken scoping behavior involving variables declared in defs and such, which only became apparent when the strict_undefined flag was turned on. .. change:: :tags: bug :tickets: 191 Can now use strict_undefined at the same time args passed to def() are used by other elements of the <%def> tag. .. changelog:: :version: 0.7.0 :released: Fri Mar 30 2012 .. change:: :tags: feature :tickets: 125 Added new "loop" variable to templates, is provided within a % for block to provide info about the loop such as index, first/last, odd/even, etc. A migration path is also provided for legacy templates via the "enable_loop" argument available on Template, TemplateLookup, and <%page>. Thanks to Ben Trofatter for all the work on this .. change:: :tags: feature :tickets: Added a real check for "reserved" names, that is names which are never pulled from the context and cannot be passed to the template.render() method. Current names are "context", "loop", "UNDEFINED". .. change:: :tags: feature :tickets: 95 The html_error_template() will now apply Pygments highlighting to the source code displayed in the traceback, if Pygments if available. Courtesy Ben Trofatter .. change:: :tags: feature :tickets: 147 Added support for context managers, i.e. "% with x as e:/ % endwith" support. Courtesy Ben Trofatter .. change:: :tags: feature :tickets: 185 Added class-level flag to CacheImpl "pass_context"; when True, the keyword argument 'context' will be passed to get_or_create() containing the Mako Context object. .. change:: :tags: bug :tickets: 182 Fixed some Py3K resource warnings due to filehandles being implicitly closed. .. change:: :tags: bug :tickets: 186 Fixed endless recursion bug when nesting multiple def-calls with content. Thanks to Jeff Dairiki. .. change:: :tags: feature :tickets: Added Jinja2 to the example benchmark suite, courtesy Vincent Férotin Older Versions ============== .. changelog:: :version: 0.6.2 :released: Thu Feb 2 2012 .. change:: :tags: bug :tickets: 86, 20 The ${{"foo":"bar"}} parsing issue is fixed!! The legendary Eevee has slain the dragon!. Also fixes quoting issue at. .. changelog:: :version: 0.6.1 :released: Sat Jan 28 2012 .. change:: :tags: bug :tickets: Added special compatibility for the 0.5.0 Cache() constructor, which was preventing file version checks and not allowing Mako 0.6 to recompile the module files. .. changelog:: :version: 0.6.0 :released: Sat Jan 21 2012 .. change:: :tags: feature :tickets: Template caching has been converted into a plugin system, whereby the usage of Beaker is just the default plugin. Template and TemplateLookup now accept a string "cache_impl" parameter which refers to the name of a cache plugin, defaulting to the name 'beaker'. New plugins can be registered as pkg_resources entrypoints under the group "mako.cache", or registered directly using mako.cache.register_plugin(). The core plugin is the mako.cache.CacheImpl class. .. change:: :tags: feature :tickets: Added support for Beaker cache regions in templates. Usage of regions should be considered as superseding the very obsolete idea of passing in backend options, timeouts, etc. within templates. .. change:: :tags: feature :tickets: The 'put' method on Cache is now 'set'. 'put' is there for backwards compatibility. .. change:: :tags: feature :tickets: The <%def>, <%block> and <%page> tags now accept any argument named "cache_*", and the key minus the "cache_" prefix will be passed as keyword arguments to the CacheImpl methods. .. change:: :tags: feature :tickets: Template and TemplateLookup now accept an argument cache_args, which refers to a dictionary containing cache parameters. The cache_dir, cache_url, cache_type, cache_timeout arguments are deprecated (will probably never be removed, however) and can be passed now as cache_args={'url':, 'type':'memcached', 'timeout':50, 'dir':'/path/to/some/directory'} .. change:: :tags: feature/bug :tickets: 180 Can now refer to context variables within extra arguments to <%block>, <%def>, i.e. <%block name="foo" cache_key="${somekey}">. Filters can also be used in this way, i.e. <%def name="foo()" filter="myfilter"> then template.render(myfilter=some_callable) .. change:: :tags: feature :tickets: 178 Added "--var name=value" option to the mako-render script, allows passing of kw to the template from the command line. .. change:: :tags: feature :tickets: 181 Added module_writer argument to Template, TemplateLookup, allows a callable to be passed which takes over the writing of the template's module source file, so that special environment-specific steps can be taken. .. change:: :tags: bug :tickets: 142 The exception message in the html_error_template is now escaped with the HTML filter. .. change:: :tags: bug :tickets: 173 Added "white-space:pre" style to html_error_template() for code blocks so that indentation is preserved .. change:: :tags: bug :tickets: 175 The "benchmark" example is now Python 3 compatible (even though several of those old template libs aren't available on Py3K, so YMMV) .. changelog:: :version: 0.5.0 :released: Wed Sep 28 2011 .. change:: :tags: :tickets: 174 A Template is explicitly disallowed from having a url that normalizes to relative outside of the root. That is, if the Lookup is based at /home/mytemplates, an include that would place the ultimate template at /home/mytemplates/../some_other_directory, i.e. outside of /home/mytemplates, is disallowed. This usage was never intended despite the lack of an explicit check. The main issue this causes is that module files can be written outside of the module root (or raise an error, if file perms aren't set up), and can also lead to the same template being cached in the lookup under multiple, relative roots. TemplateLookup instead has always supported multiple file roots for this purpose. .. changelog:: :version: 0.4.2 :released: Fri Aug 5 2011 .. change:: :tags: :tickets: 170 Fixed bug regarding <%call>/def calls w/ content whereby the identity of the "caller" callable inside the <%def> would be corrupted by the presence of another <%call> in the same block. .. change:: :tags: :tickets: 169 Fixed the babel plugin to accommodate <%block> .. changelog:: :version: 0.4.1 :released: Wed Apr 6 2011 .. change:: :tags: :tickets: 164 New tag: <%block>. A variant on <%def> that evaluates its contents in-place. Can be named or anonymous, the named version is intended for inheritance layouts where any given section can be surrounded by the <%block> tag in order for it to become overrideable by inheriting templates, without the need to specify a top-level <%def> plus explicit call. Modified scoping and argument rules as well as a more strictly enforced usage scheme make it ideal for this purpose without at all replacing most other things that defs are still good for. Lots of new docs. .. change:: :tags: :tickets: 165 a slight adjustment to the "highlight" logic for generating template bound stacktraces. Will stick to known template source lines without any extra guessing. .. changelog:: :version: 0.4.0 :released: Sun Mar 6 2011 .. change:: :tags: :tickets: A 20% speedup for a basic two-page inheritance setup rendering a table of escaped data (see http://techspot.zzzeek.org/2010/11/19/quick-mako-vs.-jinja-speed-test/). A few configurational changes which affect those in the I-don't-do-unicode camp should be noted below. .. change:: :tags: :tickets: The FastEncodingBuffer is now used by default instead of cStringIO or StringIO, regardless of whether output_encoding is set to None or not. FEB is faster than both. Only StringIO allows bytestrings of unknown encoding to pass right through, however - while it is of course not recommended to send bytestrings of unknown encoding to the output stream, this mode of usage can be re-enabled by setting the flag bytestring_passthrough to True. .. change:: :tags: :tickets: disable_unicode mode requires that output_encoding be set to None - it also forces the bytestring_passthrough flag to True. .. change:: :tags: :tickets: 156 the <%namespace> tag raises an error if the 'template' and 'module' attributes are specified at the same time in one tag. A different class is used for each case which allows a reduction in runtime conditional logic and function call overhead. .. change:: :tags: :tickets: 159 the keys() in the Context, as well as it's internal _data dictionary, now include just what was specified to render() as well as Mako builtins 'caller', 'capture'. The contents of __builtin__ are no longer copied. Thanks to Daniel Lopez for pointing this out. .. changelog:: :version: 0.3.6 :released: Sat Nov 13 2010 .. change:: :tags: :tickets: 126 Documentation is on Sphinx. .. change:: :tags: :tickets: 154 Beaker is now part of "extras" in setup.py instead of "install_requires". This to produce a lighter weight install for those who don't use the caching as well as to conform to Pyramid deployment practices. .. change:: :tags: :tickets: 153 The Beaker import (or attempt thereof) is delayed until actually needed; this to remove the performance penalty from startup, particularly for "single execution" environments such as shell scripts. .. change:: :tags: :tickets: 155 Patch to lexer to not generate an empty '' write in the case of backslash-ended lines. .. change:: :tags: :tickets: 148 Fixed missing **extra collection in setup.py which prevented setup.py from running 2to3 on install. .. change:: :tags: :tickets: New flag on Template, TemplateLookup - strict_undefined=True, will cause variables not found in the context to raise a NameError immediately, instead of defaulting to the UNDEFINED value. .. change:: :tags: :tickets: The range of Python identifiers that are considered "undefined", meaning they are pulled from the context, has been trimmed back to not include variables declared inside of expressions (i.e. from list comprehensions), as well as in the argument list of lambdas. This to better support the strict_undefined feature. The change should be fully backwards-compatible but involved a little bit of tinkering in the AST code, which hadn't really been touched for a couple of years, just FYI. .. changelog:: :version: 0.3.5 :released: Sun Oct 24 2010 .. change:: :tags: :tickets: 141 The <%namespace> tag allows expressions for the `file` argument, i.e. with ${}. The `context` variable, if needed, must be referenced explicitly. .. change:: :tags: :tickets: ${} expressions embedded in tags, such as <%foo:bar x="${...}">, now allow multiline Python expressions. .. change:: :tags: :tickets: Fixed previously non-covered regular expression, such that using a ${} expression inside of a tag element that doesn't allow them raises a CompileException instead of silently failing. .. change:: :tags: :tickets: 151 Added a try/except around "import markupsafe". This to support GAE which can't run markupsafe. No idea whatsoever if the install_requires in setup.py also breaks GAE, couldn't get an answer on this. .. changelog:: :version: 0.3.4 :released: Tue Jun 22 2010 .. change:: :tags: :tickets: Now using MarkupSafe for HTML escaping, i.e. in place of cgi.escape(). Faster C-based implementation and also escapes single quotes for additional security. Supports the __html__ attribute for the given expression as well. When using "disable_unicode" mode, a pure Python HTML escaper function is used which also quotes single quotes. Note that Pylons by default doesn't use Mako's filter - check your environment.py file. .. change:: :tags: :tickets: 137 Fixed call to "unicode.strip" in exceptions.text_error_template which is not Py3k compatible. .. changelog:: :version: 0.3.3 :released: Mon May 31 2010 .. change:: :tags: :tickets: 135 Added conditional to RichTraceback such that if no traceback is passed and sys.exc_info() has been reset, the formatter just returns blank for the "traceback" portion. .. change:: :tags: :tickets: 131 Fixed sometimes incorrect usage of exc.__class__.__name__ in html/text error templates when using Python 2.4 .. change:: :tags: :tickets: Fixed broken @property decorator on template.last_modified .. change:: :tags: :tickets: 132 Fixed error formatting when a stacktrace line contains no line number, as in when inside an eval/exec-generated function. .. change:: :tags: :tickets: When a .py is being created, the tempfile where the source is stored temporarily is now made in the same directory as that of the .py file. This ensures that the two files share the same filesystem, thus avoiding cross-filesystem synchronization issues. Thanks to Charles Cazabon. .. changelog:: :version: 0.3.2 :released: Thu Mar 11 2010 .. change:: :tags: :tickets: 116 Calling a def from the top, via template.get_def(...).render() now checks the argument signature the same way as it did in 0.2.5, so that TypeError is not raised. reopen of .. changelog:: :version: 0.3.1 :released: Sun Mar 7 2010 .. change:: :tags: :tickets: 129 Fixed incorrect dir name in setup.py .. changelog:: :version: 0.3.0 :released: Fri Mar 5 2010 .. change:: :tags: :tickets: 123 Python 2.3 support is dropped. .. change:: :tags: :tickets: 119 Python 3 support is added ! See README.py3k for installation and testing notes. .. change:: :tags: :tickets: 127 Unit tests now run with nose. .. change:: :tags: :tickets: 99 Source code escaping has been simplified. In particular, module source files are now generated with the Python "magic encoding comment", and source code is passed through mostly unescaped, except for that code which is regenerated from parsed Python source. This fixes usage of unicode in <%namespace:defname> tags. .. change:: :tags: :tickets: 122 RichTraceback(), html_error_template().render(), text_error_template().render() now accept "error" and "traceback" as optional arguments, and these are now actually used. .. change:: :tags: :tickets: The exception output generated when format_exceptions=True will now be as a Python unicode if it occurred during render_unicode(), or an encoded string if during render(). .. change:: :tags: :tickets: 112 A percent sign can be emitted as the first non-whitespace character on a line by escaping it as in "%%". .. change:: :tags: :tickets: 94 Template accepts empty control structure, i.e. % if: %endif, etc. .. change:: :tags: :tickets: 116 The <%page args> tag can now be used in a base inheriting template - the full set of render() arguments are passed down through the inherits chain. Undeclared arguments go into **pageargs as usual. .. change:: :tags: :tickets: 109 defs declared within a <%namespace> section, an uncommon feature, have been improved. The defs no longer get doubly-rendered in the body() scope, and now allow local variable assignment without breakage. .. change:: :tags: :tickets: 128 Windows paths are handled correctly if a Template is passed only an absolute filename (i.e. with c: drive etc.) and no URI - the URI is converted to a forward-slash path and module_directory is treated as a windows path. .. change:: :tags: :tickets: 73 TemplateLookup raises TopLevelLookupException for a given path that is a directory, not a filename, instead of passing through to the template to generate IOError. .. changelog:: :version: 0.2.6 :released: .. change:: :tags: :tickets: Fix mako function decorators to preserve the original function's name in all cases. Patch from Scott Torborg. .. change:: :tags: :tickets: 118 Support the <%namespacename:defname> syntax in the babel extractor. .. change:: :tags: :tickets: 88 Further fixes to unicode handling of .py files with the html_error_template. .. changelog:: :version: 0.2.5 :released: Mon Sep 7 2009 .. change:: :tags: :tickets: Added a "decorator" kw argument to <%def>, allows custom decoration functions to wrap rendering callables. Mainly intended for custom caching algorithms, not sure what other uses there may be (but there may be). Examples are in the "filtering" docs. .. change:: :tags: :tickets: 101 When Mako creates subdirectories in which to store templates, it uses the more permissive mode of 0775 instead of 0750, helping out with certain multi-process scenarios. Note that the mode is always subject to the restrictions of the existing umask. .. change:: :tags: :tickets: 104 Fixed namespace.__getattr__() to raise AttributeError on attribute not found instead of RuntimeError. .. change:: :tags: :tickets: 97 Added last_modified accessor to Template, returns the time.time() when the module was created. .. change:: :tags: :tickets: 102 Fixed lexing support for whitespace around '=' sign in defs. .. change:: :tags: :tickets: 108 Removed errant "lower()" in the lexer which was causing tags to compile with case-insensitive names, thus messing up custom <%call> names. .. change:: :tags: :tickets: 110 added "mako.__version__" attribute to the base module. .. changelog:: :version: 0.2.4 :released: Tue Dec 23 2008 .. change:: :tags: :tickets: Fixed compatibility with Jython 2.5b1. .. changelog:: :version: 0.2.3 :released: Sun Nov 23 2008 .. change:: :tags: :tickets: the <%namespacename:defname> syntax described at http://techspot.zzzeek.org/?p=28 has now been added as a built in syntax, and is recommended as a more modern syntax versus <%call expr="expression">. The %call tag itself will always remain, with <%namespacename:defname> presenting a more HTML-like alternative to calling defs, both plain and nested. Many examples of the new syntax are in the "Calling a def with embedded content" section of the docs. .. change:: :tags: :tickets: added support for Jython 2.5. .. change:: :tags: :tickets: cache module now uses Beaker's CacheManager object directly, so that all cache types are included. memcached is available as both "ext:memcached" and "memcached", the latter for backwards compatibility. .. change:: :tags: :tickets: added "cache" accessor to Template, Namespace. e.g. ${local.cache.get('somekey')} or template.cache.invalidate_body() .. change:: :tags: :tickets: added "cache_enabled=True" flag to Template, TemplateLookup. Setting this to False causes cache operations to "pass through" and execute every time; this flag should be integrated in Pylons with its own cache_enabled configuration setting. .. change:: :tags: :tickets: 92 the Cache object now supports invalidate_def(name), invalidate_body(), invalidate_closure(name), invalidate(key), which will remove the given key from the cache, if it exists. The cache arguments (i.e. storage type) are derived from whatever has been already persisted for that template. .. change:: :tags: :tickets: For cache changes to work fully, Beaker 1.1 is required. 1.0.1 and up will work as well with the exception of cache expiry. Note that Beaker 1.1 is **required** for applications which use dynamically generated keys, since previous versions will permanently store state in memory for each individual key, thus consuming all available memory for an arbitrarily large number of distinct keys. .. change:: :tags: :tickets: 93 fixed bug whereby an <%included> template with <%page> args named the same as a __builtin__ would not honor the default value specified in <%page> .. change:: :tags: :tickets: 88 fixed the html_error_template not handling tracebacks from normal .py files with a magic encoding comment .. change:: :tags: :tickets: RichTraceback() now accepts an optional traceback object to be used in place of sys.exc_info()[2]. html_error_template() and text_error_template() accept an optional render()-time argument "traceback" which is passed to the RichTraceback object. .. change:: :tags: :tickets: added ModuleTemplate class, which allows the construction of a Template given a Python module generated by a previous Template. This allows Python modules alone to be used as templates with no compilation step. Source code and template source are optional but allow error reporting to work correctly. .. change:: :tags: :tickets: 90 fixed Python 2.3 compat. in mako.pyparser .. change:: :tags: :tickets: fix Babel 0.9.3 compatibility; stripping comment tags is now optional (and enabled by default). .. changelog:: :version: 0.2.2 :released: Mon Jun 23 2008 .. change:: :tags: :tickets: 87 cached blocks now use the current context when rendering an expired section, instead of the original context passed in .. change:: :tags: :tickets: fixed a critical issue regarding caching, whereby a cached block would raise an error when called within a cache-refresh operation that was initiated after the initiating template had completed rendering. .. changelog:: :version: 0.2.1 :released: Mon Jun 16 2008 .. change:: :tags: :tickets: fixed bug where 'output_encoding' parameter would prevent render_unicode() from returning a unicode object. .. change:: :tags: :tickets: bumped magic number, which forces template recompile for this version (fixes incompatible compile symbols from 0.1 series). .. change:: :tags: :tickets: added a few docs for cache options, specifically those that help with memcached. .. changelog:: :version: 0.2.0 :released: Tue Jun 3 2008 .. change:: :tags: :tickets: Speed improvements (as though we needed them, but people contributed and there you go): .. change:: :tags: :tickets: 77 added "bytestring passthru" mode, via `disable_unicode=True` argument passed to Template or TemplateLookup. All unicode-awareness and filtering is turned off, and template modules are generated with the appropriate magic encoding comment. In this mode, template expressions can only receive raw bytestrings or Unicode objects which represent straight ASCII, and render_unicode() may not be used if multibyte characters are present. When enabled, speed improvement around 10-20%. (courtesy anonymous guest) .. change:: :tags: :tickets: 76 inlined the "write" function of Context into a local template variable. This affords a 12-30% speedup in template render time. (idea courtesy same anonymous guest) .. change:: :tags: :tickets: New Features, API changes: .. change:: :tags: :tickets: 62 added "attr" accessor to namespaces. Returns attributes configured as module level attributes, i.e. within <%! %> sections. i.e.: # somefile.html <%! foo = 27 %> # some other template <%namespace name="myns" file="somefile.html"/> ${myns.attr.foo} The slight backwards incompatibility here is, you can't have namespace defs named "attr" since the "attr" descriptor will occlude it. .. change:: :tags: :tickets: 78 cache_key argument can now render arguments passed directly to the %page or %def, i.e. <%def name="foo(x)" cached="True" cache_key="${x}"/> .. change:: :tags: :tickets: some functions on Context are now private: _push_buffer(), _pop_buffer(), caller_stack._push_frame(), caller_stack._pop_frame(). .. change:: :tags: :tickets: 56, 81 added a runner script "mako-render" which renders standard input as a template to stdout .. change:: :tags: bugfixes :tickets: 83, 84 can now use most names from __builtins__ as variable names without explicit declaration (i.e. 'id', 'exception', 'range', etc.) .. change:: :tags: bugfixes :tickets: 84 can also use builtin names as local variable names (i.e. dict, locals) (came from fix for) .. change:: :tags: bugfixes :tickets: 68 fixed bug in python generation when variable names are used with identifiers like "else", "finally", etc. inside them .. change:: :tags: bugfixes :tickets: 69 fixed codegen bug which occured when using <%page> level caching, combined with an expression-based cache_key, combined with the usage of <%namespace import="*"/> - fixed lexer exceptions not cleaning up temporary files, which could lead to a maximum number of file descriptors used in the process .. change:: :tags: bugfixes :tickets: 71 fixed issue with inline format_exceptions that was producing blank exception pages when an inheriting template is present .. change:: :tags: bugfixes :tickets: format_exceptions will apply the encoding options of html_error_template() to the buffered output .. change:: :tags: bugfixes :tickets: 75 rewrote the "whitespace adjuster" function to work with more elaborate combinations of quotes and comments .. changelog:: :version: 0.1.10 :released: .. change:: :tags: :tickets: fixed propagation of 'caller' such that nested %def calls within a <%call> tag's argument list propigates 'caller' to the %call function itself (propigates to the inner calls too, this is a slight side effect which previously existed anyway) .. change:: :tags: :tickets: fixed bug where local.get_namespace() could put an incorrect "self" in the current context .. change:: :tags: :tickets: fixed another namespace bug where the namespace functions did not have access to the correct context containing their 'self' and 'parent' .. changelog:: :version: 0.1.9 :released: .. change:: :tags: :tickets: 47 filters.Decode filter can also accept a non-basestring object and will call str() + unicode() on it .. change:: :tags: :tickets: 53 comments can be placed at the end of control lines, i.e. if foo: # a comment,, thanks to Paul Colomiets .. change:: :tags: :tickets: 16 fixed expressions and page tag arguments and with embedded newlines in CRLF templates, follow up to, thanks Eric Woroshow .. change:: :tags: :tickets: 51 added an IOError catch for source file not found in RichTraceback exception reporter .. changelog:: :version: 0.1.8 :released: Tue Jun 26 2007 .. change:: :tags: :tickets: variable names declared in render methods by internal codegen prefixed by "__M_" to prevent name collisions with user code .. change:: :tags: :tickets: 45 added a Babel (http://babel.edgewall.org/) extractor entry point, allowing extraction of gettext messages directly from mako templates via Babel .. change:: :tags: :tickets: fix to turbogears plugin to work with dot-separated names (i.e. load_template('foo.bar')). also takes file extension as a keyword argument (default is 'mak'). .. change:: :tags: :tickets: 35 more tg fix: fixed, allowing string-based templates with tgplugin even if non-compatible args were sent .. changelog:: :version: 0.1.7 :released: Wed Jun 13 2007 .. change:: :tags: :tickets: one small fix to the unit tests to support python 2.3 .. change:: :tags: :tickets: a slight hack to how cache.py detects Beaker's memcached, works around unexplained import behavior observed on some python 2.3 installations .. changelog:: :version: 0.1.6 :released: Fri May 18 2007 .. change:: :tags: :tickets: caching is now supplied directly by Beaker, which has all of MyghtyUtils merged into it now. The latest Beaker (0.7.1) also fixes a bug related to how Mako was using the cache API. .. change:: :tags: :tickets: 34 fix to module_directory path generation when the path is "./" .. change:: :tags: :tickets: 35 TGPlugin passes options to string-based templates .. change:: :tags: :tickets: 28 added an explicit stack frame step to template runtime, which allows much simpler and hopefully bug-free tracking of 'caller', fixes .. change:: :tags: :tickets: if plain Python defs are used with <%call>, a decorator @runtime.supports_callable exists to ensure that the "caller" stack is properly handled for the def. .. change:: :tags: :tickets: 37 fix to RichTraceback and exception reporting to get template source code as a unicode object .. change:: :tags: :tickets: 39 html_error_template includes options "full=True", "css=True" which control generation of HTML tags, CSS .. change:: :tags: :tickets: 40 added the 'encoding_errors' parameter to Template/TemplateLookup for specifying the error handler associated with encoding to 'output_encoding' .. change:: :tags: :tickets: 37 the Template returned by html_error_template now defaults to output_encoding=sys.getdefaultencoding(), encoding_errors='htmlentityreplace' .. change:: :tags: :tickets: control lines, i.e. % lines, support backslashes to continue long lines (#32) .. change:: :tags: :tickets: fixed codegen bug when defining <%def> within <%call> within <%call> .. change:: :tags: :tickets: leading utf-8 BOM in template files is honored according to pep-0263 .. changelog:: :version: 0.1.5 :released: Sat Mar 31 2007 .. change:: :tags: :tickets: 26 AST expression generation - added in just about everything expression-wise from the AST module .. change:: :tags: :tickets: 27 AST parsing, properly detects imports of the form "import foo.bar" .. change:: :tags: :tickets: fix to lexing of <%docs> tag nested in other tags .. change:: :tags: :tickets: 29 fix to context-arguments inside of <%include> tag which broke during 0.1.4 .. change:: :tags: :tickets: added "n" filter, disables *all* filters normally applied to an expression via <%page> or default_filters (but not those within the filter) .. change:: :tags: :tickets: added buffer_filters argument, defines filters applied to the return value of buffered/cached/filtered %defs, after all filters 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 passing special attributes or objects. .. changelog:: :version: 0.1.4 :released: Sat Mar 10 2007 .. change:: :tags: :tickets: got defs-within-defs to be cacheable .. change:: :tags: :tickets: 23 fixes to code parsing/whitespace adjusting where plain python comments may contain quote characters .. change:: :tags: :tickets: fix to variable scoping for identifiers only referenced within functions .. change:: :tags: :tickets: added a path normalization step to lookup so URIs like "/foo/bar/../etc/../foo" pre-process the ".." tokens before checking the filesystem .. change:: :tags: :tickets: fixed/improved "caller" semantics so that undefined caller is "UNDEFINED", propigates __nonzero__ method so it evaulates to False if not present, True otherwise. this way you can say % if caller:\n ${caller.body()}\n% endif .. change:: :tags: :tickets: <%include> has an "args" attribute that can pass arguments to the called template (keyword arguments only, must be declared in that page's <%page> tag.) .. change:: :tags: :tickets: <%include> plus arguments is also programmatically available via self.include_file(, **kwargs) .. change:: :tags: :tickets: 24 further escaping added for multibyte expressions in %def, %call attributes .. changelog:: :version: 0.1.3 :released: Wed Feb 21 2007 .. change:: :tags: :tickets: ***Small Syntax Change*** - the single line comment character is now *two* hash signs, i.e. "## this is a comment". This avoids a common collection with CSS selectors. .. change:: :tags: :tickets: the magic "coding" comment (i.e. # coding:utf-8) will still work with either one "#" sign or two for now; two is preferred going forward, i.e. ## coding:. .. change:: :tags: :tickets: new multiline comment form: "<%doc> a comment " .. change:: :tags: :tickets: UNDEFINED evaluates to False .. change:: :tags: :tickets: improvement to scoping of "caller" variable when using <%call> tag .. change:: :tags: :tickets: added lexer error for unclosed control-line (%) line .. change:: :tags: :tickets: added "preprocessor" argument to Template, TemplateLookup - is a single callable or list of callables which will be applied to the template text before lexing. given the text as an argument, returns the new text. .. change:: :tags: :tickets: added mako.ext.preprocessors package, contains one preprocessor so far: 'convert_comments', which will convert single # comments to the new ## format .. changelog:: :version: 0.1.2 :released: Thu Feb 1 2007 .. change:: :tags: :tickets: 11 fix to parsing of code/expression blocks to insure that non-ascii characters, combined with a template that indicates a non-standard encoding, are expanded into backslash-escaped glyphs before being AST parsed .. change:: :tags: :tickets: all template lexing converts the template to unicode first, to immediately catch any encoding issues and ensure internal unicode representation. .. change:: :tags: :tickets: added module_filename argument to Template to allow specification of a specific module file .. change:: :tags: :tickets: 14 added modulename_callable to TemplateLookup to allow a function to determine module filenames (takes filename, uri arguments). used for .. change:: :tags: :tickets: added optional input_encoding flag to Template, to allow sending a unicode() object with no magic encoding comment .. change:: :tags: :tickets: "expression_filter" argument in <%page> applies only to expressions .. change:: :tags: "unicode" :tickets: added "default_filters" argument to Template, TemplateLookup. applies only to expressions, gets prepended to "expression_filter" arg from <%page>. defaults to, so that all expressions get stringified into u'' by default (this is what Mako already does). By setting to [], expressions are passed through raw. .. change:: :tags: :tickets: added "imports" argument to Template, TemplateLookup. so you can predefine a list of import statements at the top of the template. can be used in conjunction with default_filters. .. change:: :tags: :tickets: 16 support for CRLF templates...whoops ! welcome to all the windows users. .. change:: :tags: :tickets: small fix to local variable propigation for locals that are conditionally declared .. change:: :tags: :tickets: got "top level" def calls to work, i.e. template.get_def("somedef").render() .. changelog:: :version: 0.1.1 :released: Sun Jan 14 2007 .. change:: :tags: :tickets: 8 buffet plugin supports string-based templates, allows ToscaWidgets to work .. change:: :tags: :tickets: AST parsing fixes: fixed TryExcept identifier parsing .. change:: :tags: :tickets: removed textmate tmbundle from contrib and into separate SVN location; windows users cant handle those files, setuptools not very good at "pruning" certain directories .. change:: :tags: :tickets: fix so that "cache_timeout" parameter is propigated .. change:: :tags: :tickets: fix to expression filters so that string conversion (actually unicode) properly occurs before filtering .. change:: :tags: :tickets: better error message when a lookup is attempted with a template that has no lookup .. change:: :tags: :tickets: implemented "module" attribute for namespace .. change:: :tags: :tickets: fix to code generation to correctly track multiple defs with the same name .. change:: :tags: :tickets: 9 "directories" can be passed to TemplateLookup as a scalar in which case it gets converted to a list Mako-1.0.3/doc/_sources/defs.txt0000644000076500000240000004245412613724132017231 0ustar classicstaff00000000000000.. _defs_toplevel: =============== Defs and Blocks =============== ``<%def>`` and ``<%block>`` are two tags that both demarcate any block of text and/or code. They both exist within generated Python as a callable function, i.e., a Python ``def``. They differ in their scope and calling semantics. Whereas ``<%def>`` provides a construct that is very much like a named Python ``def``, the ``<%block>`` is more layout oriented. Using Defs ========== The ``<%def>`` tag requires a ``name`` attribute, where the ``name`` references a Python function signature: .. sourcecode:: mako <%def name="hello()"> hello world To invoke the ``<%def>``, it is normally called as an expression: .. sourcecode:: mako the def: ${hello()} If the ``<%def>`` is not nested inside of another ``<%def>``, it's known as a **top level def** and can be accessed anywhere in the template, including above where it was defined. All defs, top level or not, have access to the current contextual namespace in exactly the same way their containing template does. Suppose the template below is executed with the variables ``username`` and ``accountdata`` inside the context: .. sourcecode:: mako Hello there ${username}, how are ya. Lets see what your account says: ${account()} <%def name="account()"> Account for ${username}:
% for row in accountdata: Value: ${row}
% endfor The ``username`` and ``accountdata`` variables are present within the main template body as well as the body of the ``account()`` def. Since defs are just Python functions, you can define and pass arguments to them as well: .. sourcecode:: mako ${account(accountname='john')} <%def name="account(accountname, type='regular')"> account name: ${accountname}, type: ${type} When you declare an argument signature for your def, they are required to follow normal Python conventions (i.e., all arguments are required except keyword arguments with a default value). This is in contrast to using context-level variables, which evaluate to ``UNDEFINED`` if you reference a name that does not exist. Calling Defs from Other Files ----------------------------- Top level ``<%def>``\ s are **exported** by your template's module, and can be called from the outside; including from other templates, as well as normal Python code. Calling a ``<%def>`` from another template is something like using an ``<%include>`` -- except you are calling a specific function within the template, not the whole template. The remote ``<%def>`` call is also a little bit like calling functions from other modules in Python. There is an "import" step to pull the names from another template into your own template; then the function or functions are available. To import another template, use the ``<%namespace>`` tag: .. sourcecode:: mako <%namespace name="mystuff" file="mystuff.html"/> The above tag adds a local variable ``mystuff`` to the current scope. Then, just call the defs off of ``mystuff``: .. sourcecode:: mako ${mystuff.somedef(x=5,y=7)} The ``<%namespace>`` tag also supports some of the other semantics of Python's ``import`` statement, including pulling names into the local variable space, or using ``*`` to represent all names, using the ``import`` attribute: .. sourcecode:: mako <%namespace file="mystuff.html" import="foo, bar"/> This is just a quick intro to the concept of a **namespace**, which is a central Mako concept that has its own chapter in these docs. For more detail and examples, see :ref:`namespaces_toplevel`. Calling Defs Programmatically ----------------------------- You can call defs programmatically from any :class:`.Template` object using the :meth:`~.Template.get_def()` method, which returns a :class:`.DefTemplate` object. This is a :class:`.Template` subclass which the parent :class:`.Template` creates, and is usable like any other template: .. sourcecode:: python from mako.template import Template template = Template(""" <%def name="hi(name)"> hi ${name}! <%def name="bye(name)"> bye ${name}! """) print(template.get_def("hi").render(name="ed")) print(template.get_def("bye").render(name="ed")) Defs within Defs ---------------- The def model follows regular Python rules for closures. Declaring ``<%def>`` inside another ``<%def>`` declares it within the parent's **enclosing scope**: .. sourcecode:: mako <%def name="mydef()"> <%def name="subdef()"> a sub def i'm the def, and the subcomponent is ${subdef()} Just like Python, names that exist outside the inner ``<%def>`` exist inside it as well: .. sourcecode:: mako <% x = 12 %> <%def name="outer()"> <% y = 15 %> <%def name="inner()"> inner, x is ${x}, y is ${y} outer, x is ${x}, y is ${y} Assigning to a name inside of a def declares that name as local to the scope of that def (again, like Python itself). This means the following code will raise an error: .. sourcecode:: mako <% x = 10 %> <%def name="somedef()"> ## error ! somedef, x is ${x} <% x = 27 %> ...because the assignment to ``x`` declares ``x`` as local to the scope of ``somedef``, rendering the "outer" version unreachable in the expression that tries to render it. .. _defs_with_content: Calling a Def with Embedded Content and/or Other Defs ----------------------------------------------------- A flip-side to def within def is a def call with content. This is where you call a def, and at the same time declare a block of content (or multiple blocks) that can be used by the def being called. The main point of such a call is to create custom, nestable tags, just like any other template language's custom-tag creation system -- where the external tag controls the execution of the nested tags and can communicate state to them. Only with Mako, you don't have to use any external Python modules, you can define arbitrarily nestable tags right in your templates. To achieve this, the target def is invoked using the form ``<%namespacename:defname>`` instead of the normal ``${}`` syntax. This syntax, introduced in Mako 0.2.3, is functionally equivalent to another tag known as ``%call``, which takes the form ``<%call expr='namespacename.defname(args)'>``. While ``%call`` is available in all versions of Mako, the newer style is probably more familiar looking. The ``namespace`` portion of the call is the name of the **namespace** in which the def is defined -- in the most simple cases, this can be ``local`` or ``self`` to reference the current template's namespace (the difference between ``local`` and ``self`` is one of inheritance -- see :ref:`namespaces_builtin` for details). When the target def is invoked, a variable ``caller`` is placed in its context which contains another namespace containing the body and other defs defined by the caller. The body itself is referenced by the method ``body()``. Below, we build a ``%def`` that operates upon ``caller.body()`` to invoke the body of the custom tag: .. sourcecode:: mako <%def name="buildtable()">
${caller.body()}
<%self:buildtable> I am the table body. This produces the output (whitespace formatted): .. sourcecode:: html
I am the table body.
Using the older ``%call`` syntax looks like: .. sourcecode:: mako <%def name="buildtable()">
${caller.body()}
<%call expr="buildtable()"> I am the table body. The ``body()`` can be executed multiple times or not at all. This means you can use def-call-with-content to build iterators, conditionals, etc: .. sourcecode:: mako <%def name="lister(count)"> % for x in range(count): ${caller.body()} % endfor <%self:lister count="${3}"> hi Produces: .. sourcecode:: html hi hi hi Notice above we pass ``3`` as a Python expression, so that it remains as an integer. A custom "conditional" tag: .. sourcecode:: mako <%def name="conditional(expression)"> % if expression: ${caller.body()} % endif <%self:conditional expression="${4==4}"> i'm the result Produces: .. sourcecode:: html i'm the result But that's not all. The ``body()`` function also can handle arguments, which will augment the local namespace of the body callable. The caller must define the arguments which it expects to receive from its target def using the ``args`` attribute, which is a comma-separated list of argument names. Below, our ``<%def>`` calls the ``body()`` of its caller, passing in an element of data from its argument: .. sourcecode:: mako <%def name="layoutdata(somedata)"> % for item in somedata: % for col in item: % endfor % endfor
${caller.body(col=col)}
<%self:layoutdata somedata="${[[1,2,3],[4,5,6],[7,8,9]]}" args="col">\ Body data: ${col}\ Produces: .. sourcecode:: html
Body data: 1 Body data: 2 Body data: 3
Body data: 4 Body data: 5 Body data: 6
Body data: 7 Body data: 8 Body data: 9
You don't have to stick to calling just the ``body()`` function. The caller can define any number of callables, allowing the ``<%call>`` tag to produce whole layouts: .. sourcecode:: mako <%def name="layout()"> ## a layout def
${caller.header()}
${caller.body()}
## calls the layout def <%self:layout> <%def name="header()"> I am the header <%def name="sidebar()">
  • sidebar 1
  • sidebar 2
this is the body The above layout would produce: .. sourcecode:: html
I am the header
this is the body
The number of things you can do with ``<%call>`` and/or the ``<%namespacename:defname>`` calling syntax is enormous. You can create form widget libraries, such as an enclosing ``
`` tag and nested HTML input elements, or portable wrapping schemes using ``
`` or other elements. You can create tags that interpret rows of data, such as from a database, providing the individual columns of each row to a ``body()`` callable which lays out the row any way it wants. Basically anything you'd do with a "custom tag" or tag library in some other system, Mako provides via ``<%def>`` tags and plain Python callables which are invoked via ``<%namespacename:defname>`` or ``<%call>``. .. _blocks: Using Blocks ============ The ``<%block>`` tag introduces some new twists on the ``<%def>`` tag which make it more closely tailored towards layout. .. versionadded:: 0.4.1 An example of a block: .. sourcecode:: mako <%block> this is a block. In the above example, we define a simple block. The block renders its content in the place that it's defined. Since the block is called for us, it doesn't need a name and the above is referred to as an **anonymous block**. So the output of the above template will be: .. sourcecode:: html this is a block. So in fact the above block has absolutely no effect. Its usefulness comes when we start using modifiers. Such as, we can apply a filter to our block: .. sourcecode:: mako <%block filter="h"> this is some escaped html. or perhaps a caching directive: .. sourcecode:: mako <%block cached="True" cache_timeout="60"> This content will be cached for 60 seconds. Blocks also work in iterations, conditionals, just like defs: .. sourcecode:: mako % if some_condition: <%block>condition is met % endif While the block renders at the point it is defined in the template, the underlying function is present in the generated Python code only once, so there's no issue with placing a block inside of a loop or similar. Anonymous blocks are defined as closures in the local rendering body, so have access to local variable scope: .. sourcecode:: mako % for i in range(1, 4): <%block>i is ${i} % endfor Using Named Blocks ------------------ Possibly the more important area where blocks are useful is when we do actually give them names. Named blocks are tailored to behave somewhat closely to Jinja2's block tag, in that they define an area of a layout which can be overridden by an inheriting template. In sharp contrast to the ``<%def>`` tag, the name given to a block is global for the entire template regardless of how deeply it's nested: .. sourcecode:: mako <%block name="header"> <%block name="title">Title</%block> ${next.body()} The above example has two named blocks "``header``" and "``title``", both of which can be referred to by an inheriting template. A detailed walkthrough of this usage can be found at :ref:`inheritance_toplevel`. Note above that named blocks don't have any argument declaration the way defs do. They still implement themselves as Python functions, however, so they can be invoked additional times beyond their initial definition: .. sourcecode:: mako
<%block name="pagecontrol"> previous page | next page ## some content
${pagecontrol()}
The content referenced by ``pagecontrol`` above will be rendered both above and below the ```` tags. To keep things sane, named blocks have restrictions that defs do not: * The ``<%block>`` declaration cannot have any argument signature. * The name of a ``<%block>`` can only be defined once in a template -- an error is raised if two blocks of the same name occur anywhere in a single template, regardless of nesting. A similar error is raised if a top level def shares the same name as that of a block. * A named ``<%block>`` cannot be defined within a ``<%def>``, or inside the body of a "call", i.e. ``<%call>`` or ``<%namespacename:defname>`` tag. Anonymous blocks can, however. Using Page Arguments in Named Blocks ------------------------------------ A named block is very much like a top level def. It has a similar restriction to these types of defs in that arguments passed to the template via the ``<%page>`` tag aren't automatically available. Using arguments with the ``<%page>`` tag is described in the section :ref:`namespaces_body`, and refers to scenarios such as when the ``body()`` method of a template is called from an inherited template passing arguments, or the template is invoked from an ``<%include>`` tag with arguments. To allow a named block to share the same arguments passed to the page, the ``args`` attribute can be used: .. sourcecode:: mako <%page args="post"/> <%block name="post_prose" args="post"> ${post.content} Where above, if the template is called via a directive like ``<%include file="post.mako" args="post=post" />``, the ``post`` variable is available both in the main body as well as the ``post_prose`` block. Similarly, the ``**pageargs`` variable is present, in named blocks only, for those arguments not explicit in the ``<%page>`` tag: .. sourcecode:: mako <%block name="post_prose"> ${pageargs['post'].content} The ``args`` attribute is only allowed with named blocks. With anonymous blocks, the Python function is always rendered in the same scope as the call itself, so anything available directly outside the anonymous block is available inside as well. Mako-1.0.3/doc/_sources/filtering.txt0000644000076500000240000002442512613724132020271 0ustar classicstaff00000000000000.. _filtering_toplevel: ======================= Filtering and Buffering ======================= Expression Filtering ==================== As described in the chapter :ref:`syntax_toplevel`, the "``|``" operator can be applied to a "``${}``" expression to apply escape filters to the output: .. sourcecode:: mako ${"this is some text" | u} The above expression applies URL escaping to the expression, and produces ``this+is+some+text``. The built-in escape flags are: * ``u`` : URL escaping, provided by ``urllib.quote_plus(string.encode('utf-8'))`` * ``h`` : HTML escaping, provided by ``markupsafe.escape(string)`` .. versionadded:: 0.3.4 Prior versions use ``cgi.escape(string, True)``. * ``x`` : XML escaping * ``trim`` : whitespace trimming, provided by ``string.strip()`` * ``entity`` : produces HTML entity references for applicable strings, derived from ``htmlentitydefs`` * ``unicode`` (``str`` on Python 3): produces a Python unicode string (this function is applied by default) * ``decode.``: decode input into a Python unicode with the specified encoding * ``n`` : disable all default filtering; only filters specified in the local expression tag will be applied. To apply more than one filter, separate them by a comma: .. sourcecode:: mako ${" some value " | h,trim} The above produces ``<tag>some value</tag>``, with no leading or trailing whitespace. The HTML escaping function is applied first, the "trim" function second. Naturally, you can make your own filters too. A filter is just a Python function that accepts a single string argument, and returns the filtered result. The expressions after the ``|`` operator draw upon the local namespace of the template in which they appear, meaning you can define escaping functions locally: .. sourcecode:: mako <%! def myescape(text): return "" + text + "" %> Here's some tagged text: ${"text" | myescape} Or from any Python module: .. sourcecode:: mako <%! import myfilters %> Here's some tagged text: ${"text" | myfilters.tagfilter} A page can apply a default set of filters to all expression tags using the ``expression_filter`` argument to the ``%page`` tag: .. sourcecode:: mako <%page expression_filter="h"/> Escaped text: ${"some html"} Result: .. sourcecode:: html Escaped text: <html>some html</html> .. _filtering_default_filters: The ``default_filters`` Argument -------------------------------- In addition to the ``expression_filter`` argument, the ``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 ``disable_unicode=True`` is set in which case it defaults to ``["str"]``: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=['unicode']) To replace the usual ``unicode``/``str`` function with a specific encoding, the ``decode`` filter can be substituted: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=['decode.utf8']) To disable ``default_filters`` entirely, set it to an empty list: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=[]) Any string name can be added to ``default_filters`` where it will be added to all expressions as a filter. The filters are applied from left to right, meaning the leftmost filter is applied first. .. sourcecode:: python t = Template(templatetext, default_filters=['unicode', 'myfilter']) To ease the usage of ``default_filters`` with custom filters, you can also add imports (or other code) to all templates using the ``imports`` argument: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=['unicode', 'myfilter'], imports=['from mypackage import myfilter']) The above will generate templates something like this: .. sourcecode:: python # .... from mypackage import myfilter def render_body(context): context.write(myfilter(unicode("some text"))) 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 ``<%page>`` tag as well as in ``default_filters``. Such as: .. sourcecode:: mako ${'myexpression' | n} will render ``myexpression`` with no filtering of any kind, and: .. sourcecode:: mako ${'myexpression' | n,trim} will render ``myexpression`` using the ``trim`` filter only. Filtering Defs and Blocks ========================= The ``%def`` and ``%block`` tags have an argument called ``filter`` which will apply the given list of filter functions to the output of the ``%def``: .. sourcecode:: mako <%def name="foo()" filter="h, trim"> this is bold When the ``filter`` attribute is applied to a def as above, the def is automatically **buffered** as well. This is described next. 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 :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 function is the content it produced, which is then delivered to your template just like any other expression substitution, except that normally, this is not the case; the return value of ``${somedef()}`` is simply the empty string ``''``. By the time you receive this empty string, the output of ``somedef()`` has been sent to the underlying buffer. You may not want this effect, if for example you are doing something like this: .. sourcecode:: mako ${" results " + somedef() + " more results "} If the ``somedef()`` function produced the content "``somedef's results``", the above template would produce this output: .. sourcecode:: html somedef's results results more results This is because ``somedef()`` fully executes before the expression returns the results of its concatenation; the concatenation in turn receives just the empty string as its middle expression. Mako provides two ways to work around this. One is by applying buffering to the ``%def`` itself: .. sourcecode:: mako <%def name="somedef()" buffered="True"> somedef's results The above definition will generate code similar to this: .. sourcecode:: python def somedef(): context.push_buffer() try: context.write("somedef's results") finally: buf = context.pop_buffer() return buf.getvalue() So that the content of ``somedef()`` is sent to a second buffer, 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 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 be useful for a filtering function that wishes to apply a transformation to the text as a whole. The other way to buffer the output of a def or any Mako callable is by using the built-in ``capture`` function. This function performs an operation similar to the above buffering operation except it is specified by the caller. .. sourcecode:: mako ${" results " + capture(somedef) + " more results "} Note that the first argument to the ``capture`` function is **the function itself**, not the result of calling it. This is because the ``capture`` function takes over the job of actually calling the target function, after setting up a buffered environment. To send arguments to the function, just send them to ``capture`` instead: .. sourcecode:: mako ${capture(somedef, 17, 'hi', use_paging=True)} The above call is equivalent to the unbuffered call: .. sourcecode:: mako ${somedef(17, 'hi', use_paging=True)} Decorating ========== .. versionadded:: 0.2.5 Somewhat like 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 intent of this function is to allow the creation of custom cache logic, but there may be other uses as well. ``decorator`` is intended to be used with a regular Python function, such as one defined in a library module. Here we'll illustrate the python function defined in the template for simplicities' sake: .. sourcecode:: mako <%! def bar(fn): def decorate(context, *args, **kw): context.write("BAR") fn(*args, **kw) context.write("BAR") return '' return decorate %> <%def name="foo()" decorator="bar"> this is foo ${foo()} 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 :func:`.capture` callable in the ``mako.runtime`` module (available in templates as just ``runtime``): .. sourcecode:: mako <%! def bar(fn): def decorate(context, *args, **kw): return "BAR" + runtime.capture(context, fn, *args, **kw) + "BAR" return decorate %> <%def name="foo()" decorator="bar"> this is foo ${foo()} 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 :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. Mako-1.0.3/doc/_sources/index.txt0000644000076500000240000000041412613724132017405 0ustar classicstaff00000000000000Table of Contents ================= .. toctree:: :maxdepth: 2 usage syntax defs runtime namespaces inheritance filtering unicode caching changelog Indices and Tables ------------------ * :ref:`genindex` * :ref:`search` Mako-1.0.3/doc/_sources/inheritance.txt0000644000076500000240000004642212613724132020600 0ustar classicstaff00000000000000.. _inheritance_toplevel: =========== 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. Using template inheritance, two or more templates can organize themselves into an **inheritance chain**, where content and functions from all involved templates can be intermixed. The general paradigm of template inheritance is this: if a template ``A`` inherits from template ``B``, then template ``A`` agrees to send the executional control to template ``B`` at runtime (``A`` is called the **inheriting** template). Template ``B``, the **inherited** template, then makes decisions as to what resources from ``A`` shall be executed. In practice, it looks like this. Here's a hypothetical inheriting template, ``index.html``: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%block name="header"> this is some header content this is the body content. And ``base.html``, the inherited template: .. sourcecode:: mako ## base.html
<%block name="header"/>
${self.body()} 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 :doc:`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
this is some header content
this is the body content. ...and that is template inheritance in a nutshell. The main idea is that the methods that you call upon ``self`` always correspond to the topmost definition of that method. Very much the way ``self`` works in a Python class, even though Mako is not actually using Python class inheritance to implement this functionality. (Mako doesn't take the "inheritance" metaphor too seriously; while useful to setup some commonly recognized semantics, a textual template is not very much like an object-oriented class construct in practice). Nesting Blocks ============== The named blocks defined in an inherited template can also be nested within other blocks. The name given to each block is globally accessible via any inheriting template. We can add a new block ``title`` to our ``header`` block: .. sourcecode:: mako ## base.html
<%block name="header">

<%block name="title"/>

${self.body()} The inheriting template can name either or both of ``header`` and ``title``, separately or nested themselves: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%block name="header"> this is some header content ${parent.header()} <%block name="title"> this is the title this is the body content. Note when we overrode ``header``, we added an extra call ``${parent.header()}`` in order to invoke the parent's ``header`` block in addition to our own. That's described in more detail below, in :ref:`parent_namespace`. Rendering a Named Block Multiple Times ====================================== Recall from the section :ref:`blocks` that a named block is just like a ``<%def>``, with some different usage rules. We can call one of our named sections distinctly, for example a section that is used more than once, such as the title of a page: .. sourcecode:: mako ${self.title()} <%block name="header">

<%block name="title"/>

${self.body()} Where above an inheriting template can define ``<%block name="title">`` just once, and it will be used in the base template both in the ```` section as well as the ``<h2>``. But what about Defs? ==================== The previous example used the ``<%block>`` tag to produce areas of content to be overridden. Before Mako 0.4.1, there wasn't any such tag -- instead there was only the ``<%def>`` tag. As it turns out, named blocks and defs are largely interchangeable. The def simply doesn't call itself automatically, and has more open-ended naming and scoping rules that are more flexible and similar to Python itself, but less suited towards layout. The first example from this chapter using defs would look like: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%def name="header()"> this is some header content </%def> this is the body content. And ``base.html``, the inherited template: .. sourcecode:: mako ## base.html <html> <body> <div class="header"> ${self.header()} </div> ${self.body()} <div class="footer"> ${self.footer()} </div> </body> </html> <%def name="header()"/> <%def name="footer()"> this is the footer </%def> Above, we illustrate that defs differ from blocks in that their definition and invocation are defined in two separate places, instead of at once. You can *almost* do exactly what a block does if you put the two together: .. sourcecode:: mako <div class="header"> <%def name="header()"></%def>${self.header()} </div> The ``<%block>`` is obviously more streamlined than the ``<%def>`` for this kind of usage. In addition, the above "inline" approach with ``<%def>`` does not work with nesting: .. sourcecode:: mako <head> <%def name="header()"> <title> ## this won't work ! <%def name="title()">default title</%def>${self.title()} ${self.header()} Where above, the ``title()`` def, because it's a def within a def, is not part of the template's exported namespace and will not be part of ``self``. If the inherited template did define its own ``title`` def at the top level, it would be called, but the "default title" above is not present at all on ``self`` no matter what. For this to work as expected you'd instead need to say: .. sourcecode:: mako <%def name="header()"> ${self.title()} ${self.header()} <%def name="title()"/> That is, ``title`` is defined outside of any other defs so that it is in the ``self`` namespace. It works, but the definition needs to be potentially far away from the point of render. A named block is always placed in the ``self`` namespace, regardless of nesting, so this restriction is lifted: .. sourcecode:: mako ## base.html <%block name="header"> <%block name="title"/> The above template defines ``title`` inside of ``header``, and an inheriting template can define one or both in **any** configuration, nested inside each other or not, in order for them to be used: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%block name="title"> the title <%block name="header"> the header So while the ``<%block>`` tag lifts the restriction of nested blocks not being available externally, in order to achieve this it *adds* the restriction that all block names in a single template need 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 ======================================================== Sometimes you have an inheritance chain that spans more than two templates. Or maybe you don't, but you'd like to build your system such that extra inherited templates can be inserted in the middle of a chain where they would be smoothly integrated. If each template wants to define its layout just within its main body, you can't just call ``self.body()`` to get at the inheriting template's body, since that is only the topmost body. To get at the body of the *next* template, you call upon the namespace ``next``, which is the namespace of the template **immediately following** the current template. Lets change the line in ``base.html`` which calls upon ``self.body()`` to instead call upon ``next.body()``: .. sourcecode:: mako ## base.html
<%block name="header"/>
${next.body()} Lets also add an intermediate template called ``layout.html``, which inherits from ``base.html``: .. sourcecode:: mako ## layout.html <%inherit file="base.html"/>
    <%block name="toolbar">
  • selection 1
  • selection 2
  • selection 3
${next.body()}
And finally change ``index.html`` to inherit from ``layout.html`` instead: .. sourcecode:: mako ## index.html <%inherit file="layout.html"/> ## .. rest of template In this setup, each call to ``next.body()`` will render the body of the next template in the inheritance chain (which can be written as ``base.html -> layout.html -> index.html``). Control is still first passed to the bottommost template ``base.html``, and ``self`` still references the topmost definition of any particular def. The output we get would be: .. sourcecode:: html
this is some header content
  • selection 1
  • selection 2
  • selection 3
this is the body content.
So above, we have the ````, ```` and ``header``/``footer`` layout of ``base.html``, we have the ``
    `` and ``mainlayout`` section of ``layout.html``, and the main body of ``index.html`` as well as its overridden ``header`` def. The ``layout.html`` template is inserted into the middle of the chain without ``base.html`` having to change anything. Without the ``next`` namespace, only the main body of ``index.html`` could be used; there would be no way to call ``layout.html``'s body content. .. _parent_namespace: 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 namespace of the template **immediately preceding** the current template. What's useful about this namespace is that defs or blocks can call upon their overridden versions. This is not as hard as it sounds and is very much like using the ``super`` keyword in Python. Lets modify ``index.html`` to augment the list of selections provided by the ``toolbar`` function in ``layout.html``: .. sourcecode:: mako ## index.html <%inherit file="layout.html"/> <%block name="header"> this is some header content <%block name="toolbar"> ## call the parent's toolbar first ${parent.toolbar()}
  • selection 4
  • selection 5
  • this is the body content. Above, we implemented a ``toolbar()`` function, which is meant to override the definition of ``toolbar`` within the inherited template ``layout.html``. However, since we want the content from that of ``layout.html`` as well, we call it via the ``parent`` namespace whenever we want it's content, in this case before we add our own selections. So the output for the whole thing is now: .. sourcecode:: html
    this is some header content
    • selection 1
    • selection 2
    • selection 3
    • selection 4
    • selection 5
    this is the body content.
    and you're now a template inheritance ninja! Using ``<%include>`` with Template Inheritance ============================================== A common source of confusion is the behavior of the ``<%include>`` tag, often in conjunction with its interaction within template inheritance. Key to understanding the ``<%include>`` tag is that it is a *dynamic*, e.g. runtime, include, and not a static include. The ``<%include>`` is only processed as the template renders, and not at inheritance setup time. When encountered, the referenced template is run fully as an entirely separate template with no linkage to any current inheritance structure. If the tag were on the other hand a *static* include, this would allow source within the included template to interact within the same inheritance context as the calling template, but currently Mako has no static include facility. In practice, this means that ``<%block>`` elements defined in an ``<%include>`` file will not interact with corresponding ``<%block>`` elements in the calling template. A common mistake is along these lines: .. sourcecode:: mako ## partials.mako <%block name="header"> Global Header ## parent.mako <%include file="partials.mako"> ## child.mako <%inherit file="parent.mako"> <%block name="header"> Custom Header Above, one might expect that the ``"header"`` block declared in ``child.mako`` might be invoked, as a result of it overriding the same block present in ``parent.mako`` via the include for ``partials.mako``. But this is not the case. Instead, ``parent.mako`` will invoke ``partials.mako``, which then invokes ``"header"`` in ``partials.mako``, and then is finished rendering. Nothing from ``child.mako`` will render; there is no interaction between the ``"header"`` block in ``child.mako`` and the ``"header"`` block in ``partials.mako``. Instead, ``parent.mako`` must explicitly state the inheritance structure. In order to call upon specific elements of ``partials.mako``, we will call upon it as a namespace: .. sourcecode:: mako ## partials.mako <%block name="header"> Global Header ## parent.mako <%namespace name="partials" file="partials.mako"/> <%block name="header"> ${partials.header()} ## child.mako <%inherit file="parent.mako"> <%block name="header"> Custom Header Where above, ``parent.mako`` states the inheritance structure that ``child.mako`` is to participate within. ``partials.mako`` only defines defs/blocks that can be used on a per-name basis. Another scenario is below, which results in both ``"SectionA"`` blocks being rendered for the ``child.mako`` document: .. sourcecode:: mako ## base.mako ${self.body()} <%block name="SectionA"> base.mako ## parent.mako <%inherit file="base.mako"> <%include file="child.mako"> ## child.mako <%block name="SectionA"> child.mako The resolution is similar; instead of using ``<%include>``, we call upon the blocks of ``child.mako`` using a namespace: .. sourcecode:: mako ## parent.mako <%inherit file="base.mako"> <%namespace name="child" file="child.mako"> <%block name="SectionA"> ${child.SectionA()} .. _inheritance_attr: Inheritable Attributes ====================== 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: .. sourcecode:: mako <%! class_ = "grey" %>
    ${self.body()}
    If an inheriting template overrides ``class_`` to be ``"white"``, as in: .. sourcecode:: mako <%! class_ = "white" %> <%inherit file="parent.html"/> This is the body you'll get output like: .. sourcecode:: html
    This is the body
    .. seealso:: :ref:`namespace_attr_for_includes` - a more sophisticated example using :attr:`.Namespace.attr`. Mako-1.0.3/doc/_sources/namespaces.txt0000644000076500000240000003435612613724132020431 0ustar classicstaff00000000000000.. _namespaces_toplevel: ========== Namespaces ========== Namespaces are used to organize groups of defs into categories, and also to "import" defs from other files. If the file ``components.html`` defines these two defs: .. sourcecode:: mako ## components.html <%def name="comp1()"> this is comp1 <%def name="comp2(x)"> this is comp2, x is ${x} you can make another file, for example ``index.html``, that pulls those two defs into a namespace called ``comp``: .. sourcecode:: mako ## index.html <%namespace name="comp" file="components.html"/> Here's comp1: ${comp.comp1()} Here's comp2: ${comp.comp2(x=5)} The ``comp`` variable above is an instance of :class:`.Namespace`, a **proxy object** which delivers method calls to the underlying template callable using the 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 "``.``" operator. When ``import`` is used, the ``name`` attribute is optional. .. sourcecode:: mako <%namespace file="components.html" import="comp1, comp2"/> Heres comp1: ${comp1()} Heres comp2: ${comp2(x=5)} ``import`` also supports the "``*``" operator: .. sourcecode:: mako <%namespace file="components.html" import="*"/> Heres comp1: ${comp1()} Heres comp2: ${comp2(x=5)} The names imported by the ``import`` attribute take precedence over any names that exist within the current context. .. note:: In current versions of Mako, usage of ``import='*'`` is known to decrease performance of the template. This will be fixed in a future release. The ``file`` argument allows expressions -- if looking for context variables, the ``context`` must be named explicitly: .. sourcecode:: mako <%namespace name="dyn" file="${context['namespace_name']}"/> Ways to Call Namespaces ======================= There are essentially four ways to call a function from a namespace. The "expression" format, as described previously. Namespaces are just Python objects with functions on them, and can be used in expressions like any other function: .. sourcecode:: mako ${mynamespace.somefunction('some arg1', 'some arg2', arg3='some arg3', arg4='some arg4')} Synonymous with the "expression" format is the "custom tag" format, when a "closed" tag is used. This format, introduced in Mako 0.2.3, allows the usage of a "custom" Mako tag, with the function arguments passed in using named attributes: .. sourcecode:: mako <%mynamespace:somefunction arg1="some arg1" arg2="some arg2" arg3="some arg3" arg4="some arg4"/> When using tags, the values of the arguments are taken as literal strings by default. To embed Python expressions as arguments, use the embedded expression format: .. sourcecode:: mako <%mynamespace:somefunction arg1="${someobject.format()}" arg2="${somedef(5, 12)}"/> The "custom tag" format is intended mainly for namespace functions which recognize body content, which in Mako is known as a "def with embedded content": .. sourcecode:: mako <%mynamespace:somefunction arg1="some argument" args="x, y"> Some record: ${x}, ${y} The "classic" way to call defs with embedded content is the ``<%call>`` tag: .. sourcecode:: mako <%call expr="mynamespace.somefunction(arg1='some argument')" args="x, y"> Some record: ${x}, ${y} For information on how to construct defs that embed content from the caller, see :ref:`defs_with_content`. .. _namespaces_python_modules: Namespaces from Regular Python Modules ====================================== Namespaces can also import regular Python functions from modules. These callables need to take at least one argument, ``context``, an instance of :class:`.Context`. A module file ``some/module.py`` might contain the callable: .. sourcecode:: python def my_tag(context): context.write("hello world") return '' A template can use this module via: .. sourcecode:: mako <%namespace name="hw" module="some.module"/> ${hw.my_tag()} Note that the ``context`` argument is not needed in the call; the :class:`.Namespace` tag creates a locally-scoped callable which takes care of it. The ``return ''`` is so that the def does not dump a ``None`` into the output stream -- the return value of any def is rendered after the def completes, in addition to whatever was passed to :meth:`.Context.write` within its body. If your def is to be called in an "embedded content" context, that is as described in :ref:`defs_with_content`, you should use the :func:`.supports_caller` decorator, which will ensure that Mako will ensure the correct "caller" variable is available when your def is called, supporting embedded content: .. sourcecode:: python from mako.runtime import supports_caller @supports_caller def my_tag(context): context.write("
    ") context['caller'].body() context.write("
    ") return '' Capturing of output is available as well, using the outside-of-templates version of the :func:`.capture` function, which accepts the "context" as its first argument: .. sourcecode:: python from mako.runtime import supports_caller, capture @supports_caller def my_tag(context): return "
    %s
    " % \ capture(context, context['caller'].body, x="foo", y="bar") Declaring Defs in Namespaces ============================ The ``<%namespace>`` tag supports the definition of ``<%def>``\ s directly inside the tag. These defs become part of the namespace like any other function, and will override the definitions pulled in from a remote template or module: .. sourcecode:: mako ## define a namespace <%namespace name="stuff"> <%def name="comp1()"> comp1 ## then call it ${stuff.comp1()} .. _namespaces_body: The ``body()`` Method ===================== Every namespace that is generated from a template contains a method called ``body()``. This method corresponds to the main body of the template, and plays its most important roles when using inheritance relationships as well as def-calls-with-content. Since the ``body()`` method is available from a namespace just like all the other defs defined in a template, what happens if you send arguments to it? By default, the ``body()`` method accepts no positional arguments, and for usefulness in inheritance scenarios will by default dump all keyword arguments into a dictionary called ``pageargs``. But if you actually want to get at the keyword arguments, Mako recommends you define your own argument signature explicitly. You do this via using the ``<%page>`` tag: .. sourcecode:: mako <%page args="x, y, someval=8, scope='foo', **kwargs"/> A template which defines the above signature requires that the variables ``x`` and ``y`` are defined, defines default values for ``someval`` and ``scope``, and sets up ``**kwargs`` to receive all other keyword arguments. If ``**kwargs`` or similar is not present, the argument ``**pageargs`` gets tacked on by Mako. When the template is called as a top-level template (i.e. via :meth:`~.Template.render`) or via the ``<%include>`` tag, the values for these arguments will be pulled from the ``Context``. In all other cases, i.e. via calling the ``body()`` method, the arguments are taken as ordinary arguments from the method call. So above, the body might be called as: .. sourcecode:: mako ${self.body(5, y=10, someval=15, delta=7)} The :class:`.Context` object also supplies a :attr:`~.Context.kwargs` accessor, for cases when you'd like to pass along the top level context arguments to a ``body()`` callable: .. sourcecode:: mako ${next.body(**context.kwargs)} The usefulness of calls like the above become more apparent when one works with inheriting templates. For more information on this, as well as the meanings of the names ``self`` and ``next``, see :ref:`inheritance_toplevel`. .. _namespaces_builtin: Built-in Namespaces =================== The namespace is so great that Mako gives your template one (or two) for free. The names of these namespaces are ``local`` and ``self``. Other built-in namespaces include ``parent`` and ``next``, which are optional and are described in :ref:`inheritance_toplevel`. .. _namespace_local: ``local`` --------- The ``local`` namespace is basically the namespace for the currently executing template. This means that all of the top level defs defined in your template, as well as your template's ``body()`` function, are also available off of the ``local`` namespace. The ``local`` namespace is also where properties like ``uri``, ``filename``, and ``module`` and the ``get_namespace`` method can be particularly useful. .. _namespace_self: ``self`` -------- The ``self`` namespace, in the case of a template that does not use inheritance, is synonymous with ``local``. If inheritance is used, then ``self`` references the topmost template in the inheritance chain, where it is most useful for providing the ultimate form of various "method" calls which may have been overridden at various points in an inheritance chain. See :ref:`inheritance_toplevel`. Inheritable Namespaces ====================== The ``<%namespace>`` tag includes an optional attribute ``inheritable="True"``, which will cause the namespace to be attached to the ``self`` namespace. Since ``self`` is globally available throughout an inheritance chain (described in the next section), all the templates in an inheritance chain can get at the namespace imported in a super-template via ``self``. .. sourcecode:: mako ## base.html <%namespace name="foo" file="foo.html" inheritable="True"/> ${next.body()} ## somefile.html <%inherit file="base.html"/> ${self.foo.bar()} This allows a super-template to load a whole bunch of namespaces that its inheriting templates can get to, without them having to explicitly load those namespaces themselves. The ``import="*"`` part of the ``<%namespace>`` tag doesn't yet interact with the ``inheritable`` flag, so currently you have to use the explicit namespace name off of ``self``, followed by the desired function name. But more on this in a future release. Namespace API Usage Example - Static Dependencies ================================================== The ``<%namespace>`` tag at runtime produces an instance of :class:`.Namespace`. Programmatic access of :class:`.Namespace` can be used to build various kinds of scaffolding in templates and between templates. A common request is the ability for a particular template to declare "static includes" - meaning, the usage of a particular set of defs requires that certain Javascript/CSS files are present. Using :class:`.Namespace` as the object that holds together the various templates present, we can build a variety of such schemes. In particular, the :class:`.Context` has a ``namespaces`` attribute, which is a dictionary of all :class:`.Namespace` objects declared. Iterating the values of this dictionary will provide a :class:`.Namespace` object for each time the ``<%namespace>`` tag was used, anywhere within the inheritance chain. .. _namespace_attr_for_includes: Version One - Use :attr:`.Namespace.attr` ----------------------------------------- The :attr:`.Namespace.attr` attribute allows us to locate any variables declared in the ``<%! %>`` of a template. .. sourcecode:: mako ## base.mako ## base-most template, renders layout etc. ## traverse through all namespaces present, ## look for an attribute named 'includes' % for ns in context.namespaces.values(): % for incl in getattr(ns.attr, 'includes', []): ${incl} % endfor % endfor ${next.body()} ## library.mako ## library functions. <%! includes = [ '', '' ] %> <%def name="mytag()"> ${caller.body()} ## index.mako ## calling template. <%inherit file="base.mako"/> <%namespace name="foo" file="library.mako"/> <%foo:mytag> a form Above, the file ``library.mako`` declares an attribute ``includes`` inside its global ``<%! %>`` section. ``index.mako`` includes this template using the ``<%namespace>`` tag. The base template ``base.mako``, which is the inherited parent of ``index.mako`` and is reponsible for layout, then locates this attribute and iterates through its contents to produce the includes that are specific to ``library.mako``. Version Two - Use a specific named def ----------------------------------------- In this version, we put the includes into a ``<%def>`` that follows a naming convention. .. sourcecode:: mako ## base.mako ## base-most template, renders layout etc. ## traverse through all namespaces present, ## look for a %def named 'includes' % for ns in context.namespaces.values(): % if hasattr(ns, 'includes'): ${ns.includes()} % endif % endfor ${next.body()} ## library.mako ## library functions. <%def name="includes()"> <%def name="mytag()">
    ${caller.body()} ## index.mako ## calling template. <%inherit file="base.mako"/> <%namespace name="foo" file="library.mako"/> <%foo:mytag> a form In this version, ``library.mako`` declares a ``<%def>`` named ``includes``. The example works identically to the previous one, except that ``base.mako`` looks for defs named ``include`` on each namespace it examines. API Reference ============= .. autoclass:: mako.runtime.Namespace :show-inheritance: :members: .. autoclass:: mako.runtime.TemplateNamespace :show-inheritance: :members: .. autoclass:: mako.runtime.ModuleNamespace :show-inheritance: :members: .. autofunction:: mako.runtime.supports_caller .. autofunction:: mako.runtime.capture Mako-1.0.3/doc/_sources/runtime.txt0000644000076500000240000003741112613724132017770 0ustar classicstaff00000000000000.. _runtime_toplevel: ============================ The Mako Runtime Environment ============================ This section describes a little bit about the objects and built-in functions that are available in templates. .. _context: Context ======= The :class:`.Context` is the central object that is created when a template is first executed, and is responsible for handling all communication with the outside world. Within the template environment, it is available via the :ref:`reserved name ` ``context``. The :class:`.Context` includes two major components, one of which is the output buffer, which is a file-like object such as Python's ``StringIO`` or similar, and the other a dictionary of variables that can be freely referenced within a template; this dictionary is a combination of the arguments sent to the :meth:`~.Template.render` function and some built-in variables provided by Mako's runtime environment. The Buffer ---------- The buffer is stored within the :class:`.Context`, and writing to it is achieved by calling the :meth:`~.Context.write` method -- in a template this looks like ``context.write('some string')``. You usually don't need to care about this, as all text within a template, as well as all expressions provided by ``${}``, automatically send everything to this method. The cases you might want to be aware of its existence are if you are dealing with various filtering/buffering scenarios, which are described in :ref:`filtering_toplevel`, or if you want to programmatically send content to the output stream, such as within a ``<% %>`` block. .. sourcecode:: mako <% context.write("some programmatic text") %> The actual buffer may or may not be the original buffer sent to the :class:`.Context` object, as various filtering/caching scenarios may "push" a new buffer onto the context's underlying buffer stack. For this reason, just stick with ``context.write()`` and content will always go to the topmost buffer. .. _context_vars: Context Variables ----------------- When your template is compiled into a Python module, the body content is enclosed within a Python function called ``render_body``. Other top-level defs defined in the template are defined within their own function bodies which are named after the def's name with the prefix ``render_`` (i.e. ``render_mydef``). One of the first things that happens within these functions is that all variable names that are referenced within the function which are not defined in some other way (i.e. such as via assignment, module level imports, etc.) are pulled from the :class:`.Context` object's dictionary of variables. This is how you're able to freely reference variable names in a template which automatically correspond to what was passed into the current :class:`.Context`. * **What happens if I reference a variable name that is not in 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 :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. * **UNDEFINED makes it hard for me to find what name is missing** - An alternative is to specify the option ``strict_undefined=True`` to the :class:`.Template` or :class:`.TemplateLookup`. This will cause any non-present variables to raise an immediate ``NameError`` which includes the name of the variable in its message when :meth:`~.Template.render` is called -- ``UNDEFINED`` is not used. .. versionadded:: 0.3.6 * **Why not just return None?** Using ``UNDEFINED``, or raising a ``NameError`` is more explicit and allows differentiation between a value of ``None`` that was explicitly passed to the :class:`.Context` and a value that wasn't present at all. * **Why raise an exception when you call str() on it ? Why not just return a blank string?** - Mako tries to stick to the Python philosophy of "explicit is better than implicit". In this case, it's decided that the template author should be made to specifically handle a missing value rather than experiencing what may be a silent failure. Since ``UNDEFINED`` is a singleton object just like Python's ``True`` or ``False``, you can use the ``is`` operator to check for it: .. sourcecode:: mako % if someval is UNDEFINED: someval is: no value % else: someval is: ${someval} % endif Another facet of the :class:`.Context` is that its dictionary of variables is **immutable**. Whatever is set when :meth:`~.Template.render` is called is what stays. Of course, since its Python, you can hack around this and change values in the context's internal dictionary, but this will probably will not work as well as you'd think. The reason for this is that Mako in many cases creates copies of the :class:`.Context` object, which get sent to various elements of the template and inheriting templates used in an execution. So changing the value in your local :class:`.Context` will not necessarily make that value available in other parts of the template's execution. Examples of where Mako creates copies of the :class:`.Context` include within top-level def calls from the main body of the template (the context is used to propagate locally assigned variables into the scope of defs; since in the template's body they appear as inlined functions, Mako tries to make them act that way), and within an inheritance chain (each template in an inheritance chain has a different notion of ``parent`` and ``next``, which are all stored in unique :class:`.Context` instances). * **So what if I want to set values that are global to everyone within a template request?** - All you have to do is provide a dictionary to your :class:`.Context` when the template first runs, and everyone can just get/set variables from that. Lets say its called ``attributes``. Running the template looks like: .. sourcecode:: python output = template.render(attributes={}) Within a template, just reference the dictionary: .. sourcecode:: mako <% attributes['foo'] = 'bar' %> 'foo' attribute is: ${attributes['foo']} * **Why can't "attributes" be a built-in feature of the Context?** - This is an area where Mako is trying to make as few decisions about your application as it possibly can. Perhaps you don't want your templates to use this technique of assigning and sharing data, or perhaps you have a different notion of the names and kinds of data structures that should be passed around. Once again Mako would rather ask the user to be explicit. Context Methods and Accessors ----------------------------- Significant members of :class:`.Context` include: * ``context[key]`` / ``context.get(key, default=None)`` - dictionary-like accessors for the context. Normally, any variable you use in your template is automatically pulled from 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 present, like a dictionary it raises ``KeyError``. * ``keys()`` - all the names defined within this context. * ``kwargs`` - this returns a **copy** of the context's dictionary of variables. This is useful when you want to propagate the variables in the current context to a function as keyword arguments, i.e.: .. sourcecode:: mako ${next.body(**context.kwargs)} * ``write(text)`` - write some text to the current output stream. * ``lookup`` - returns the :class:`.TemplateLookup` instance that is used for all file-lookups within the current execution (even though individual :class:`.Template` instances can conceivably have different instances of a :class:`.TemplateLookup`, only the :class:`.TemplateLookup` of the originally-called :class:`.Template` gets used in a particular execution). .. _loop_context: The Loop Context ================ Within ``% for`` blocks, the :ref:`reserved name` ``loop`` is available. ``loop`` tracks the progress of the ``for`` loop and makes it easy to use the iteration state to control template behavior: .. sourcecode:: mako
      % for a in ("one", "two", "three"):
    • Item ${loop.index}: ${a}
    • % endfor
    .. versionadded:: 0.7 Iterations ---------- Regardless of the type of iterable you're looping over, ``loop`` always tracks the 0-indexed iteration count (available at ``loop.index``), its parity (through the ``loop.even`` and ``loop.odd`` bools), and ``loop.first``, a bool indicating whether the loop is on its first iteration. If your iterable provides a ``__len__`` method, ``loop`` also provides access to a count of iterations remaining at ``loop.reverse_index`` and ``loop.last``, a bool indicating whether the loop is on its last iteration; accessing these without ``__len__`` will raise a ``TypeError``. Cycling ------- Cycling is available regardless of whether the iterable you're using provides a ``__len__`` method. Prior to Mako 0.7, you might have generated a simple zebra striped list using ``enumerate``: .. sourcecode:: mako
      % for i, item in enumerate(('spam', 'ham', 'eggs')):
    • ${item}
    • % endfor
    With ``loop.cycle``, you get the same results with cleaner code and less prep work: .. sourcecode:: mako
      % for item in ('spam', 'ham', 'eggs'):
    • ${item}
    • % endfor
    Both approaches produce output like the following: .. sourcecode:: html
    • spam
    • ham
    • eggs
    Parent Loops ------------ Loop contexts can also be transparently nested, and the Mako runtime will do the right thing and manage the scope for you. You can access the parent loop context through ``loop.parent``. This allows you to reach all the way back up through the loop stack by chaining ``parent`` attribute accesses, i.e. ``loop.parent.parent....`` as long as the stack depth isn't exceeded. For example, you can use the parent loop to make a checkered table: .. sourcecode:: mako
% for consonant in 'pbj': % for vowel in 'iou': % endfor % endfor
${consonant + vowel}t
.. sourcecode:: html
pit pot put
bit bot but
jit jot jut
.. _migrating_loop: Migrating Legacy Templates that Use the Word "loop" --------------------------------------------------- .. versionchanged:: 0.7 The ``loop`` name is now :ref:`reserved ` in Mako, which means a template that refers to a variable named ``loop`` won't function correctly when used in Mako 0.7. To ease the transition for such systems, the feature can be disabled across the board for all templates, then re-enabled on a per-template basis for those templates which wish 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: .. sourcecode:: python lookup = TemplateLookup(directories=['/docs'], enable_loop=False) or: .. sourcecode:: python template = Template("some template", enable_loop=False) An individual template can make usage of the feature when ``enable_loop`` is set to ``False`` by switching it back on within the ``<%page>`` tag: .. sourcecode:: mako <%page enable_loop="True"/> % for i in collection: ${i} ${loop.index} % endfor Using the above scheme, it's safe to pass the name ``loop`` to the :meth:`.Template.render` method as well as to freely make usage of a variable named ``loop`` within a template, provided the ``<%page>`` tag doesn't override it. New templates that want to use the ``loop`` context can then set up ``<%page enable_loop="True"/>`` to use the new feature without affecting old templates. All the Built-in Names ====================== A one-stop shop for all the names Mako defines. Most of these names are instances of :class:`.Namespace`, which are described in the next section, :ref:`namespaces_toplevel`. Also, most of these names other than ``context``, ``UNDEFINED``, and ``loop`` are also present *within* the :class:`.Context` itself. The names ``context``, ``loop`` and ``UNDEFINED`` themselves can't be passed to the context and can't be substituted -- see the section :ref:`reserved_names`. * ``context`` - this is the :class:`.Context` object, introduced at :ref:`context`. * ``local`` - the namespace of the current template, described in :ref:`namespaces_builtin`. * ``self`` - the namespace of the topmost template in an inheritance chain (if any, otherwise the same as ``local``), mostly described in :ref:`inheritance_toplevel`. * ``parent`` - the namespace of the parent template in an inheritance chain (otherwise undefined); see :ref:`inheritance_toplevel`. * ``next`` - the namespace of the next template in an inheritance chain (otherwise undefined); see :ref:`inheritance_toplevel`. * ``caller`` - a "mini" namespace created when using the ``<%call>`` tag to define a "def call with content"; described in :ref:`defs_with_content`. * ``loop`` - this provides access to :class:`.LoopContext` objects when they are requested within ``% for`` loops, introduced at :ref:`loop_context`. * ``capture`` - a function that calls a given def and captures its resulting content into a string, which is returned. Usage is described in :ref:`filtering_toplevel`. * ``UNDEFINED`` - a global singleton that is applied to all otherwise uninitialized template variables that were not located within the :class:`.Context` when rendering began, unless the :class:`.Template` flag ``strict_undefined`` is set to ``True``. ``UNDEFINED`` is 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 ``<%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 makes no sense, it shouldn't; read the section :ref:`namespaces_body`. .. _reserved_names: Reserved Names -------------- Mako has a few names that are considered to be "reserved" and can't be used as variable names. .. versionchanged:: 0.7 Mako raises an error if these words are found passed to the template as context arguments, whereas in previous versions they'd be silently ignored or lead to other error messages. * ``context`` - see :ref:`context`. * ``UNDEFINED`` - see :ref:`context_vars`. * ``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 ============= .. autoclass:: mako.runtime.Context :show-inheritance: :members: .. autoclass:: mako.runtime.LoopContext :show-inheritance: :members: .. autoclass:: mako.runtime.Undefined :show-inheritance: Mako-1.0.3/doc/_sources/syntax.txt0000644000076500000240000003273112613724132017633 0ustar classicstaff00000000000000.. _syntax_toplevel: ====== Syntax ====== A Mako template is parsed from a text stream containing any kind of content, XML, HTML, email text, etc. The template can further contain Mako-specific directives which represent variable and/or expression substitutions, control structures (i.e. conditionals and loops), server-side comments, full blocks of Python code, as well as various tags that offer additional functionality. All of these constructs compile into real Python code. This means that you can leverage the full power of Python in almost every aspect of a Mako template. Expression Substitution ======================= The simplest expression is just a variable substitution. The syntax for this is the ``${}`` construct, which is inspired by Perl, Genshi, JSP EL, and others: .. sourcecode:: mako this is x: ${x} Above, the string representation of ``x`` is applied to the template's output stream. If you're wondering where ``x`` comes from, 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. The contents within the ``${}`` tag are evaluated by Python directly, so full expressions are OK: .. sourcecode:: mako pythagorean theorem: ${pow(x,2) + pow(y,2)} The results of the expression are evaluated into a string result in all cases before being rendered to the output stream, such as the above example where the expression produces a numeric result. Expression Escaping =================== Mako includes a number of built-in escaping mechanisms, including HTML, URI and XML escaping, as well as a "trim" function. These escapes can be added to an expression substitution using the ``|`` operator: .. sourcecode:: mako ${"this is some text" | u} The above expression applies URL escaping to the expression, and produces ``this+is+some+text``. The ``u`` name indicates URL escaping, whereas ``h`` represents HTML escaping, ``x`` represents XML escaping, and ``trim`` applies a trim function. Read more about built-in filtering functions, including how to make your own filter functions, in :ref:`filtering_toplevel`. Control Structures ================== A control structure refers to all those things that control the flow of a program -- conditionals (i.e. ``if``/``else``), loops (like ``while`` and ``for``), as well as things like ``try``/``except``. In Mako, control structures are written using the ``%`` marker followed by a regular Python control expression, and are "closed" by using another ``%`` marker with the tag "``end``", where "````" is the keyword of the expression: .. sourcecode:: mako % if x==5: this is some output % endif The ``%`` can appear anywhere on the line as long as no text precedes it; indentation is not significant. The full range of Python "colon" expressions are allowed here, including ``if``/``elif``/``else``, ``while``, ``for``, and even ``def``, although Mako has a built-in tag for defs which is more full-featured. .. sourcecode:: mako % for a in ['one', 'two', 'three', 'four', 'five']: % if a[0] == 't': its two or three % elif a[0] == 'f': four/five % else: one % endif % endfor The ``%`` sign can also be "escaped", if you actually want to emit a percent sign as the first non whitespace character on a line, by escaping it as in ``%%``: .. sourcecode:: mako %% some text %% some more text The Loop Context ---------------- The **loop context** provides additional information about a loop while inside of a ``% for`` structure: .. sourcecode:: mako
    % for a in ("one", "two", "three"):
  • Item ${loop.index}: ${a}
  • % endfor
See :ref:`loop_context` for more information on this feature. .. versionadded:: 0.7 Comments ======== Comments come in two varieties. The single line comment uses ``##`` as the first non-space characters on a line: .. sourcecode:: mako ## this is a comment. ...text ... A multiline version exists using ``<%doc> ...text... ``: .. sourcecode:: mako <%doc> these are comments more comments Newline Filters =============== The backslash ("``\``") character, placed at the end of any line, will consume the newline character before continuing to the next line: .. sourcecode:: mako here is a line that goes onto \ another line. The above text evaluates to: .. sourcecode:: text here is a line that goes onto another line. Python Blocks ============= Any arbitrary block of python can be dropped in using the ``<% %>`` tags: .. sourcecode:: mako this is a template <% x = db.get_resource('foo') y = [z.element for z in x if x.frobnizzle==5] %> % for elem in y: element: ${elem} % endfor Within ``<% %>``, you're writing a regular block of Python code. While the code can appear with an arbitrary level of preceding whitespace, it has to be consistently formatted with itself. Mako's compiler will adjust the block of Python to be consistent with the surrounding generated Python code. Module-level Blocks =================== A variant on ``<% %>`` is the module-level code block, denoted by ``<%! %>``. Code within these tags is executed at the module level of the template, and not within the rendering function of the template. Therefore, this code does not have access to the template's context and is only executed when the template is loaded into memory (which can be only once per application, or more, depending on the runtime environment). Use the ``<%! %>`` tags to declare your template's imports, as well as any pure-Python functions you might want to declare: .. sourcecode:: mako <%! import mylib import re def filter(text): return re.sub(r'^@', '', text) %> Any number of ``<%! %>`` blocks can be declared anywhere in a template; they will be rendered in the resulting module in a single contiguous block above all render callables, in the order in which they appear in the source template. Tags ==== The rest of what Mako offers takes place in the form of tags. All tags use the same syntax, which is similar to an XML tag except that the first character of the tag name is a ``%`` character. The tag is closed either by a contained slash character, or an explicit closing tag: .. sourcecode:: mako <%include file="foo.txt"/> <%def name="foo" buffered="True"> this is a def All tags have a set of attributes which are defined for each tag. Some of these attributes are required. Also, many attributes support **evaluation**, meaning you can embed an expression (using ``${}``) inside the attribute text: .. sourcecode:: mako <%include file="/foo/bar/${myfile}.txt"/> Whether or not an attribute accepts runtime evaluation depends on the type of tag and how that tag is compiled into the template. The best way to find out if you can stick an expression in is to try it! The lexer will tell you if it's not valid. Heres a quick summary of all the tags: ``<%page>`` ----------- This tag defines general characteristics of the template, including caching arguments, and optional lists of arguments which the template expects when invoked. .. sourcecode:: mako <%page args="x, y, z='default'"/> Or a page tag that defines caching characteristics: .. sourcecode:: mako <%page cached="True" cache_type="memory"/> Currently, only one ``<%page>`` tag gets used per template, the rest get ignored. While this will be improved in a future release, for now make sure you have only one ``<%page>`` tag defined in your template, else you may not get the results you want. The details of what ``<%page>`` is used for are described further in :ref:`namespaces_body` as well as :ref:`caching_toplevel`. ``<%include>`` -------------- A tag that is familiar from other template languages, ``%include`` is a regular joe that just accepts a file argument and calls in the rendered result of that file: .. sourcecode:: mako <%include file="header.html"/> hello world <%include file="footer.html"/> Include also accepts arguments which are available as ``<%page>`` arguments in the receiving template: .. sourcecode:: mako <%include file="toolbar.html" args="current_section='members', username='ed'"/> ``<%def>`` ---------- The ``%def`` tag defines a Python function which contains a set of content, that can be called at some other point in the template. The basic idea is simple: .. sourcecode:: mako <%def name="myfunc(x)"> this is myfunc, x is ${x} ${myfunc(7)} The ``%def`` tag is a lot more powerful than a plain Python ``def``, as the Mako compiler provides many extra services with ``%def`` that you wouldn't normally have, such as the ability to export defs as template "methods", automatic propagation of the current :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`. ``<%block>`` ------------ ``%block`` is a tag that is close to a ``%def``, except executes itself immediately in its base-most scope, and can also be anonymous (i.e. with no name): .. sourcecode:: mako <%block filter="h"> some stuff. Inspired by Jinja2 blocks, named blocks offer a syntactically pleasing way to do inheritance: .. sourcecode:: mako <%block name="header">

<%block name="title"/>

${self.body()} Blocks are introduced in :ref:`blocks` and further described in :ref:`inheritance_toplevel`. .. versionadded:: 0.4.1 ``<%namespace>`` ---------------- ``%namespace`` is Mako's equivalent of Python's ``import`` statement. It allows access to all the rendering functions and metadata of other template files, plain Python modules, as well as locally defined "packages" of functions. .. sourcecode:: mako <%namespace file="functions.html" import="*"/> The underlying object generated by ``%namespace``, an instance of :class:`.mako.runtime.Namespace`, is a central construct used in templates to reference template-specific information such as the current URI, inheritance structures, and other things that are not as hard as they sound right here. Namespaces are described in :ref:`namespaces_toplevel`. ``<%inherit>`` -------------- Inherit allows templates to arrange themselves in **inheritance chains**. This is a concept familiar in many other template languages. .. sourcecode:: mako <%inherit file="base.html"/> When using the ``%inherit`` tag, control is passed to the topmost inherited template first, which then decides how to handle calling areas of content from its inheriting templates. Mako offers a lot of flexibility in this area, including dynamic inheritance, content wrapping, and polymorphic method calls. Check it out in :ref:`inheritance_toplevel`. ``<%``\ nsname\ ``:``\ defname\ ``>`` ------------------------------------- Any user-defined "tag" can be created against a namespace by using a tag with a name of the form ``<%:>``. The closed and open formats of such a tag are equivalent to an inline expression and the ``<%call>`` tag, respectively. .. sourcecode:: mako <%mynamespace:somedef param="some value"> this is the body To create custom tags which accept a body, see :ref:`defs_with_content`. .. versionadded:: 0.2.3 ``<%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>`` ---------- The ``%doc`` tag handles multiline comments: .. sourcecode:: mako <%doc> these are comments more comments Also the ``##`` symbol as the first non-space characters on a line can be used for single line comments. ``<%text>`` ----------- This tag suspends the Mako lexer's normal parsing of Mako template directives, and returns its entire body contents as plain text. It is used pretty much to write documentation about Mako: .. sourcecode:: mako <%text filter="h"> heres some fake mako ${syntax} <%def name="x()">${x} .. _syntax_exiting_early: Exiting Early from a Template ============================= Sometimes you want to stop processing a template or ``<%def>`` method in the middle and just use the text you've accumulated so far. This is accomplished by using ``return`` statement inside a Python block. It's a good idea for the ``return`` statement to return an empty string, which prevents the Python default return value of ``None`` from being rendered by the template. This return value is for semantic purposes provided in templates via the ``STOP_RENDERING`` symbol: .. sourcecode:: mako % if not len(records): No records found. <% return STOP_RENDERING %> % endif Or perhaps: .. sourcecode:: mako <% if not len(records): return STOP_RENDERING %> In older versions of Mako, an empty string can be substituted for the ``STOP_RENDERING`` symbol: .. sourcecode:: mako <% return '' %> .. versionadded:: 1.0.2 - added the ``STOP_RENDERING`` symbol which serves as a semantic identifier for the empty string ``""`` used by a Python ``return`` statement. Mako-1.0.3/doc/_sources/unicode.txt0000644000076500000240000003247312613724132017736 0ustar classicstaff00000000000000.. _unicode_toplevel: =================== The Unicode Chapter =================== The Python language supports two ways of representing what we know as "strings", i.e. series of characters. In Python 2, the two types are ``string`` and ``unicode``, and in Python 3 they are ``bytes`` and ``string``. A key aspect of the Python 2 ``string`` and Python 3 ``bytes`` types are that they contain no information regarding what **encoding** the data is stored in. For this reason they were commonly referred to as **byte strings** on Python 2, and Python 3 makes this name more explicit. The origins of this come from Python's background of being developed before the Unicode standard was even available, back when strings were C-style strings and were just that, a series of bytes. Strings that had only values below 128 just happened to be **ASCII** strings and were printable on the console, whereas strings with values above 128 would produce all kinds of graphical characters and bells. Contrast the "byte-string" type with the "unicode/string" type. Objects of this latter type are created whenever you say something like ``u"hello world"`` (or in Python 3, just ``"hello world"``). In this case, Python represents each character in the string internally using multiple bytes per character (something similar to UTF-16). What's important is that when using the ``unicode``/``string`` type to store strings, Python knows the data's encoding; it's in its own internal format. Whereas when using the ``string``/``bytes`` type, it does not. When Python 2 attempts to treat a byte-string as a string, which means it's attempting to compare/parse its characters, to coerce it into another encoding, or to decode it to a unicode object, it has to guess what the encoding is. In this case, it will pretty much always guess the encoding as ``ascii``... and if the byte-string contains bytes above value 128, you'll get an error. Python 3 eliminates much of this confusion by just raising an error unconditionally if a byte-string is used in a character-aware context. There is one operation that Python *can* do with a non-ASCII byte-string, and it's a great source of confusion: it can dump the byte-string straight out to a stream or a file, with nary a care what the encoding is. To Python, this is pretty much like dumping any other kind of binary data (like an image) to a stream somewhere. In Python 2, it is common to see programs that embed all kinds of international characters and encodings into plain byte-strings (i.e. using ``"hello world"`` style literals) can fly right through their run, sending reams of strings out to wherever they are going, and the programmer, seeing the same output as was expressed in the input, is now under the illusion that his or her program is Unicode-compliant. In fact, their program has no unicode awareness whatsoever, and similarly has no ability to interact with libraries that *are* unicode aware. Python 3 makes this much less likely by defaulting to unicode as 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`` 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 unicode strings and other kinds of encoding conversions more intelligently, the usage of raw byte-strings quickly becomes a nightmare, since you are sending the Python interpreter collections of bytes for which it can make no intelligent decisions with regards to encoding. In Python 3 Mako only allows usage of native, unicode strings. In normal Mako operation, all parsed template constructs and 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 :ref:`the encoding of all non-ASCII templates is explicit ` (still required in Python 3), that :ref:`all non-ASCII-encoded expressions are in one way or another converted to unicode ` (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). .. _set_template_file_encoding: Specifying the Encoding of a Template File ========================================== This is the most basic encoding-related setting, and it is equivalent to Python's "magic encoding comment", as described in `pep-0263 `_. Any template that contains non-ASCII characters requires that this comment be present so that Mako can decode to unicode (and also make usage of Python's AST parsing services). Mako's lexer will use this encoding in order to convert the template source into a ``unicode`` object before continuing its parsing: .. sourcecode:: mako ## -*- coding: utf-8 -*- Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! » For the picky, the regular expression used is derived from that of the above mentioned pep: .. sourcecode:: python #.*coding[:=]\s*([-\w.]+).*\n The lexer will convert to unicode in all cases, so that if any characters exist in the template that are outside of the specified encoding (or the default of ``ascii``), the error will be immediate. As an alternative, the template encoding can be specified programmatically to either :class:`.Template` or :class:`.TemplateLookup` via the ``input_encoding`` parameter: .. sourcecode:: python t = TemplateLookup(directories=['./'], input_encoding='utf-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 ==================== The next area that encoding comes into play is in expression constructs. By default, Mako's treatment of an expression like this: .. sourcecode:: mako ${"hello world"} looks something like this: .. sourcecode:: python context.write(unicode("hello world")) In Python 3, it's just: .. sourcecode:: python context.write(str("hello world")) That is, **the output of all expressions is run through the ``unicode`` built-in**. This is the default setting, and can be modified to expect various encodings. The ``unicode`` step serves both the purpose of rendering non-string expressions into strings (such as integers or objects which contain ``__str()__`` methods), and to ensure that the final output stream is constructed as a unicode object. The main implication of this is that **any raw byte-strings that contain an encoding other than ASCII must first be decoded to a Python unicode object**. It means you can't say this in Python 2: .. sourcecode:: mako ${"voix m’a réveillé."} ## error in Python 2! You must instead say this: .. sourcecode:: mako ${u"voix m’a réveillé."} ## OK ! Similarly, if you are reading data from a file that is streaming bytes, or returning data from some object that is returning a Python byte-string containing a non-ASCII encoding, you have to explicitly decode to unicode first, such as: .. sourcecode:: mako ${call_my_object().decode('utf-8')} Note that filehandles acquired by ``open()`` in Python 3 default to returning "text", that is the decoding is done for you. See Python 3's documentation for the ``open()`` built-in for details on this. If you want a certain encoding applied to *all* expressions, override the ``unicode`` builtin with the ``decode`` built-in at the :class:`.Template` or :class:`.TemplateLookup` level: .. sourcecode:: python t = Template(templatetext, default_filters=['decode.utf8']) Note that the built-in ``decode`` object is slower than the ``unicode`` function, since unlike ``unicode`` it's not a Python built-in, and it also checks the type of the incoming data to determine if string conversion is needed first. 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 ======================== 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 :doc:`"Usage" chapter `, 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: .. sourcecode:: python 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()) :meth:`~.Template.render` will return a ``bytes`` object in Python 3 if an output encoding is specified. By default it performs no encoding and returns a native string. :meth:`~.Template.render_unicode` will return the template output as a Python ``unicode`` object (or ``string`` in Python 3): .. sourcecode:: python print(mytemplate.render_unicode()) The above method disgards the output encoding keyword argument; you can encode yourself by saying: .. sourcecode:: python print(mytemplate.render_unicode().encode('utf-8', 'replace')) Buffer Selection ---------------- Mako does play some games with the style of buffering used internally, to maximize performance. Since the buffer is by far the most heavily used object in a render operation, it's important! When calling :meth:`~.Template.render` on a template that does not specify any output encoding (i.e. it's ``ascii``), Python's ``cStringIO`` module, which cannot handle encoding of non-ASCII ``unicode`` objects (even though it can send raw byte-strings through), is used for buffering. Otherwise, a custom Mako class called ``FastEncodingBuffer`` is used, which essentially is a super dumbed-down version of ``StringIO`` that gathers all strings into a list and uses ``u''.join(elements)`` to produce the final output -- it's markedly faster than ``StringIO``. .. _unicode_disabled: Saying to Heck with It: Disabling the Usage of Unicode Entirely =============================================================== Some segments of Mako's userbase choose to make no usage of Unicode whatsoever, and instead would prefer the "pass through" approach; all string expressions in their templates return encoded byte-strings, and they would like these strings to pass right through. The only advantage to this approach is that templates need not use ``u""`` for literal strings; there's an arguable speed improvement as well since raw byte-strings generally perform slightly faster than unicode objects in Python. For these users, assuming they're sticking with Python 2, they can hit the ``disable_unicode=True`` flag as so: .. sourcecode:: python # -*- coding:utf-8 -*- from mako.template import Template t = Template("drôle de petite voix m’a réveillé.", disable_unicode=True, input_encoding='utf-8') print(t.code) The ``disable_unicode`` mode is strictly a Python 2 thing. It is not supported at all in Python 3. The generated module source code will contain elements like these: .. sourcecode:: python # -*- coding:utf-8 -*- # ...more generated code ... def render_body(context,**pageargs): context.caller_stack.push_frame() try: __M_locals = dict(pageargs=pageargs) # SOURCE LINE 1 context.write('dr\xc3\xb4le de petite voix m\xe2\x80\x99a r\xc3\xa9veill\xc3\xa9.') return '' finally: context.caller_stack.pop_frame() Where above that the string literal used within :meth:`.Context.write` 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 ``[]`` 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. This because MarkupSafe only supports Python unicode objects for non-ASCII strings. .. versionchanged:: 0.3.4 In prior versions, it used ``cgi.escape()``, which has been replaced with a function that also escapes single quotes. 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. * Don't use this option just because you don't want to learn to use Unicode properly; we aren't supporting user issues in this mode of operation. We will however offer generous help for the vast majority of users who stick to the Unicode program. * Python 3 is unicode by default, and the flag is not available when running on Python 3. Mako-1.0.3/doc/_sources/usage.txt0000644000076500000240000004266712613724132017422 0ustar classicstaff00000000000000.. _usage_toplevel: ===== 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, :ref:`syntax_toplevel`. The most basic way to create a template and render it is through the :class:`.Template` class: .. sourcecode:: python 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 ``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 ``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: .. sourcecode:: python 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: .. sourcecode:: python 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 :class:`.Template` can also load its template source code from a file, using the ``filename`` keyword argument: .. sourcecode:: python from mako.template import Template mytemplate = Template(filename='/docs/mytmpl.txt') print(mytemplate.render()) For improved performance, a :class:`.Template` which is loaded from a file can also cache the source code to its generated module on the filesystem as a regular Python module file (i.e. a ``.py`` file). To do this, just add the ``module_directory`` argument to the template: .. sourcecode:: python 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 :class:`.Template` with the same arguments is created, this module file will be automatically re-used. .. _usage_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 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 :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: .. sourcecode:: python 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 :class:`.TemplateLookup` object to it, which will search in the directory ``/docs`` for the file ``"header.txt"``. Usually, an application will store most or all of its templates as text files on the filesystem. So far, all of our examples have been a little bit contrived in order to illustrate the basic concepts. But a real application would get most or all of its templates directly from the :class:`.TemplateLookup`, using the aptly named :meth:`~.TemplateLookup.get_template` method, which accepts the URI of the desired template: .. sourcecode:: python 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 :class:`.TemplateLookup` which will look for templates in the ``/docs`` directory, and will store generated module files in the ``/tmp/mako_modules`` directory. The lookup locates templates by appending the given URI to each of its search directories; so if you gave it a URI of ``/etc/beans/info.txt``, it would search for the file ``/docs/etc/beans/info.txt``, else raise a :class:`.TopLevelNotFound` exception, which is a custom Mako exception. When the lookup locates templates, it will also assign a ``uri`` property to the :class:`.Template` which is the URI passed to the :meth:`~.TemplateLookup.get_template()` call. :class:`.Template` uses this URI to calculate the name of its module file. So in the above example, a ``templatename`` argument of ``/etc/beans/info.txt`` will create a module file ``/tmp/mako_modules/etc/beans/info.txt.py``. Setting the Collection Size --------------------------- The :class:`.TemplateLookup` also serves the important need of caching a fixed set of templates in memory at a given time, so that successive URI lookups do not result in full template compilations and/or module reloads on each request. By default, the :class:`.TemplateLookup` size is unbounded. You can specify a fixed size using the ``collection_size`` argument: .. sourcecode:: python 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 :class:`.TemplateLookup` is ``filesystem_checks``. This defaults to ``True``, and says that each time a template is returned by the :meth:`~.TemplateLookup.get_template()` method, the revision time of the original template file is checked against the last time the template was loaded, and if the file is newer will reload its contents and recompile the template. On a production system, setting ``filesystem_checks`` to ``False`` can afford a small to moderate performance increase (depending on the type of filesystem used). .. _usage_unicode: 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: .. sourcecode:: python 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 :meth:`~.Template.render` method will return a ``bytes`` object, **if** ``output_encoding`` is set. Otherwise it returns a ``string``. Additionally, the :meth:`~.Template.render_unicode()` method exists which will return the template output as a Python ``unicode`` object, or in Python 3 a ``string``: .. sourcecode:: python print(mytemplate.render_unicode()) The above method disregards the output encoding keyword argument; you can encode yourself by saying: .. sourcecode:: python 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 :ref:`unicode_toplevel`. .. _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 :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: .. sourcecode:: python 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: .. sourcecode:: python from mako import exceptions try: template = lookup.get_template(uri) print(template.render()) except: print(exceptions.html_error_template().render()) The :func:`.html_error_template` template accepts two options: specifying ``full=False`` causes only a section of an HTML document to be rendered. Specifying ``css=False`` will disable the default stylesheet from being rendered. E.g.: .. sourcecode:: python print(exceptions.html_error_template().render(full=False)) 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`: .. sourcecode:: python 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 :class:`.Template` itself, and no output stream is defined. Therefore exceptions which occur within the lookup/parse/compile stage will not be handled and will propagate normally. While the pre-render traceback usually will not include any Mako-specific lines anyway, it will mean that exceptions which occur previous to rendering and those which occur within rendering will be handled differently... so the ``try``/``except`` patterns described previously are probably of more 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: .. sourcecode:: python 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)) 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 what's included. WSGI ---- A sample WSGI application is included in the distribution 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 :class:`.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 :mod:`mako.ext.pygmentplugin`. This module is used in the generation of Mako documentation and also contains various `setuptools` entry points under the heading ``pygments.lexers``, including ``mako``, ``html+mako``, ``xml+mako`` (see the ``setup.py`` file for all the entry points). 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, including those of control lines and expressions embedded in tags. `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``: .. sourcecode:: mako
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``): .. sourcecode:: 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 :class:`.Template`/:class:`.TemplateLookup`'s ``input_encoding`` parameter). Invoking `Babel`_'s extractor at the 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: .. sourcecode:: pot #. 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')}
See the `Babel User Guide `_ for more information. .. _babel: http://babel.edgewall.org/ API Reference ============= .. autoclass:: mako.template.Template :show-inheritance: :members: .. autoclass:: mako.template.DefTemplate :show-inheritance: :members: .. autoclass:: mako.lookup.TemplateCollection :show-inheritance: :members: .. autoclass:: mako.lookup.TemplateLookup :show-inheritance: :members: .. autoclass:: mako.exceptions.RichTraceback :show-inheritance: .. py:attribute:: error the exception instance. .. py:attribute:: message the exception error message as unicode. .. py:attribute:: source source code of the file where the error occurred. If the error occurred within a compiled template, this is the template source. .. py:attribute:: lineno line number where the error occurred. If the error occurred within a compiled template, the line number is adjusted to that of the template source. .. py:attribute:: 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``). .. py:attribute:: 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. .. py:attribute:: reverse_traceback the traceback list in reverse. .. autofunction:: mako.exceptions.html_error_template .. autofunction:: mako.exceptions.text_error_template Mako-1.0.3/doc/build/0000755000076500000240000000000012613724373015022 5ustar classicstaff00000000000000Mako-1.0.3/doc/build/builder/0000755000076500000240000000000012613724373016450 5ustar classicstaff00000000000000Mako-1.0.3/doc/build/builder/__init__.py0000644000076500000240000000000012613724132020540 0ustar classicstaff00000000000000Mako-1.0.3/doc/build/builder/builders.py0000644000076500000240000000705412613724132020632 0ustar classicstaff00000000000000from sphinx.application import TemplateBridge from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.highlighting import PygmentsBridge from sphinx.jinja2glue import BuiltinTemplateLoader from pygments import highlight from pygments.lexer import RegexLexer, bygroups, using from pygments.token import * from pygments.filter import Filter, apply_filters from pygments.lexers import PythonLexer, PythonConsoleLexer from pygments.formatters import HtmlFormatter, LatexFormatter import re import os from mako.lookup import TemplateLookup from mako.template import Template from mako.ext.pygmentplugin import MakoLexer rtd = os.environ.get('READTHEDOCS', None) == 'True' class MakoBridge(TemplateBridge): def init(self, builder, *args, **kw): self.jinja2_fallback = BuiltinTemplateLoader() self.jinja2_fallback.init(builder, *args, **kw) builder.config.html_context['site_base'] = builder.config['site_base'] self.lookup = TemplateLookup( directories=builder.config.templates_path, imports=[ "from builder import util" ], #format_exceptions=True, ) def render(self, template, context): template = template.replace(".html", ".mako") context['prevtopic'] = context.pop('prev', None) context['nexttopic'] = context.pop('next', None) # RTD layout if rtd: # add variables if not present, such # as if local test of READTHEDOCS variable if 'MEDIA_URL' not in context: context['MEDIA_URL'] = "http://media.readthedocs.org/" if 'slug' not in context: context['slug'] = "mako-test-slug" if 'url' not in context: context['url'] = "/some/test/url" if 'current_version' not in context: context['current_version'] = "some_version" if 'versions' not in context: context['versions'] = [('default', '/default/')] context['docs_base'] = "http://readthedocs.org" context['toolbar'] = True context['layout'] = "rtd_layout.mako" context['pdf_url'] = "%spdf/%s/%s/%s.pdf" % ( context['MEDIA_URL'], context['slug'], context['current_version'], context['slug'] ) # local docs layout else: context['toolbar'] = False context['docs_base'] = "/" context['layout'] = "layout.mako" context.setdefault('_', lambda x:x) return self.lookup.get_template(template).render_unicode(**context) def render_string(self, template, context): # this is used for .js, .css etc. and we don't have # local copies of that stuff here so use the jinja render. return self.jinja2_fallback.render_string(template, context) class StripDocTestFilter(Filter): def filter(self, lexer, stream): for ttype, value in stream: if ttype is Token.Comment and re.match(r'#\s*doctest:', value): continue yield ttype, value def autodoc_skip_member(app, what, name, obj, skip, options): if what == 'class' and skip and name == '__init__': return False else: return skip def setup(app): # app.connect('autodoc-skip-member', autodoc_skip_member) # Mako is already in Pygments, adding the local # lexer here so that the latest syntax is available app.add_lexer('mako', MakoLexer()) app.add_config_value('site_base', "", True) Mako-1.0.3/doc/build/builder/util.py0000644000076500000240000000044612613724132017774 0ustar classicstaff00000000000000import re def striptags(text): return re.compile(r'<[^>]*>').sub('', text) def go(m): # .html with no anchor if present, otherwise "#" for top of page return m.group(1) or '#' def strip_toplevel_anchors(text): return re.compile(r'(\.html)?#[-\w]+-toplevel').sub(go, text) Mako-1.0.3/doc/build/caching.rst0000644000076500000240000003254712613724132017154 0ustar classicstaff00000000000000.. _caching_toplevel: ======= Caching ======= Any template or component can be cached using the ``cache`` argument to the ``<%page>``, ``<%def>`` or ``<%block>`` directives: .. sourcecode:: mako <%page cached="True"/> template text The above template, after being executed the first time, will store its content within a cache that by default is scoped within memory. Subsequent calls to the template's :meth:`~.Template.render` method will return content directly from the cache. When the :class:`.Template` object itself falls out of scope, its corresponding cache is garbage collected along with the template. The caching system requires that a cache backend be installed; this includes either the `Beaker `_ package or the `dogpile.cache `_, as well as any other third-party caching libraries that feature Mako integration. By default, caching will attempt to make use of Beaker. To use dogpile.cache, the ``cache_impl`` argument must be set; see this argument in the section :ref:`cache_arguments`. In addition to being available on the ``<%page>`` tag, the caching flag and all its options can be used with the ``<%def>`` tag as well: .. sourcecode:: mako <%def name="mycomp" cached="True" cache_timeout="60"> other text ... and equivalently with the ``<%block>`` tag, anonymous or named: .. sourcecode:: mako <%block cached="True" cache_timeout="60"> other text .. _cache_arguments: Cache Arguments =============== Mako has two cache arguments available on tags that are available in all cases. The rest of the arguments available are specific to a backend. The two generic tags arguments are: * ``cached="True"`` - enable caching for this ``<%page>``, ``<%def>``, or ``<%block>``. * ``cache_key`` - the "key" used to uniquely identify this content in the cache. Usually, this key is chosen automatically based on the name of the rendering callable (i.e. ``body`` when used in ``<%page>``, the name of the def when using ``<%def>``, the explicit or internally-generated name when using ``<%block>``). Using the ``cache_key`` parameter, the key can be overridden using a fixed or programmatically generated value. For example, here's a page that caches any page which inherits from it, based on the filename of the calling template: .. sourcecode:: mako <%page cached="True" cache_key="${self.filename}"/> ${next.body()} ## rest of template On a :class:`.Template` or :class:`.TemplateLookup`, the 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.: .. 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'``, indicating that the 'beaker' backend will be used. * ``cache_args`` - A dictionary of cache parameters that will be consumed by the cache backend. See :ref:`beaker_backend` and :ref:`dogpile.cache_backend` for examples. Backend-Specific Cache Arguments -------------------------------- The ``<%page>``, ``<%def>``, and ``<%block>`` tags accept any named argument that starts with the prefix ``"cache_"``. Those arguments are then packaged up and passed along to the underlying caching implementation, minus the ``"cache_"`` prefix. The actual arguments understood are determined by the backend. * :ref:`beaker_backend` - Includes arguments understood by Beaker. * :ref:`dogpile.cache_backend` - Includes arguments understood by dogpile.cache. .. _beaker_backend: Using the Beaker Cache Backend ------------------------------ When using Beaker, new implementations will want to make usage of **cache regions** so that cache configurations can be maintained externally to templates. These configurations live under named "regions" that can be referred to within templates themselves. .. versionadded:: 0.6.0 Support for Beaker cache regions. For example, suppose we would like two regions. One is a "short term" 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`: .. sourcecode:: python from beaker.cache import CacheManager manager = CacheManager(cache_regions={ 'short_term':{ 'type': 'memory', 'expire': 60 }, 'long_term':{ 'type': 'ext:memcached', 'url': '127.0.0.1:11211', 'expire': 300 } }) lookup = TemplateLookup( directories=['/path/to/templates'], module_directory='/path/to/modules', cache_impl='beaker', cache_args={ 'manager':manager } ) Our templates can then opt to cache data in one of either region, using the ``cache_region`` argument. Such as using ``short_term`` at the ``<%page>`` level: .. sourcecode:: mako <%page cached="True" cache_region="short_term"> ## ... Or, ``long_term`` at the ``<%block>`` level: .. sourcecode:: mako <%block name="header" cached="True" cache_region="long_term"> other text The Beaker backend also works without regions. There are a variety of arguments that can be passed to the ``cache_args`` dictionary, which are also allowable in templates via the ``<%page>``, ``<%block>``, and ``<%def>`` tags specific to those sections. The values given override those specified at the :class:`.TemplateLookup` or :class:`.Template` level. With the possible exception of ``cache_timeout``, these arguments are probably better off staying at the template configuration level. Each argument specified as ``cache_XYZ`` in a template tag is specified without the ``cache_`` prefix in the ``cache_args`` dictionary: * ``cache_timeout`` - number of seconds in which to invalidate the cached data. After this timeout, the content is re-generated on the next call. Available as ``timeout`` in the ``cache_args`` dictionary. * ``cache_type`` - type of caching. ``'memory'``, ``'file'``, ``'dbm'``, or ``'ext:memcached'`` (note that the string ``memcached`` is also accepted by the dogpile.cache Mako plugin, though not by Beaker itself). Available as ``type`` in the ``cache_args`` dictionary. * ``cache_url`` - (only used for ``memcached`` but required) a single IP address or a semi-colon separated list of IP address of memcache servers to use. Available as ``url`` in the ``cache_args`` dictionary. * ``cache_dir`` - in the case of the ``'file'`` and ``'dbm'`` cache types, this is the filesystem directory with which to store data files. If this option is not present, the value of ``module_directory`` is used (i.e. the directory where compiled template modules are stored). If neither option is available an exception is thrown. Available as ``dir`` in the ``cache_args`` dictionary. .. _dogpile.cache_backend: Using the dogpile.cache Backend ------------------------------- `dogpile.cache`_ is a new replacement for Beaker. It provides a modernized, slimmed down interface and is generally easier to use than Beaker. As of this writing it has not yet been released. dogpile.cache includes its own Mako cache plugin -- see :mod:`dogpile.cache.plugins.mako_cache` in the dogpile.cache documentation. Programmatic Cache Access ========================= The :class:`.Template`, as well as any template-derived :class:`.Namespace`, has 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 values: .. sourcecode:: mako <% local.cache.set("somekey", type="memory", "somevalue") %> Above, the cache associated with the ``local`` namespace is accessed and a key is placed within a memory cache. More commonly, the ``cache`` object is used to invalidate cached sections programmatically: .. sourcecode:: python template = lookup.get_template('/sometemplate.html') # invalidate the "body" of the template template.cache.invalidate_body() # invalidate an individual def template.cache.invalidate_def('somedef') # invalidate an arbitrary key template.cache.invalidate('somekey') You can access any special method or attribute of the :class:`.CacheImpl` itself using the :attr:`impl <.Cache.impl>` attribute: .. sourcecode:: python template.cache.impl.do_something_special() Note that using implementation-specific methods will mean you can't swap in a different kind of :class:`.CacheImpl` implementation at a later time. .. _cache_plugins: Cache Plugins ============= The mechanism used by caching can be plugged in using a :class:`.CacheImpl` subclass. This class implements the rudimental methods Mako needs to implement the caching API. Mako includes the :class:`.BeakerCacheImpl` class to 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 at runtime via a convenience installer :func:`.register_plugin` which accomplishes essentially the same task. An example plugin that implements a local dictionary cache: .. sourcecode:: python from mako.cache import Cacheimpl, register_plugin class SimpleCacheImpl(CacheImpl): def __init__(self, cache): super(SimpleCacheImpl, self).__init__(cache) self._cache = {} def get_or_create(self, key, creation_function, **kw): if key in self._cache: return self._cache[key] else: self._cache[key] = value = creation_function() return value def set(self, key, value, **kwargs): self._cache[key] = value def get(self, key, **kwargs): return self._cache.get(key) def invalidate(self, key, **kwargs): self._cache.pop(key, None) # optional - register the class locally register_plugin("simple", __name__, "SimpleCacheImpl") Enabling the above plugin in a template would look like: .. sourcecode:: python t = Template("mytemplate", file="mytemplate.html", cache_impl='simple') Guidelines for Writing Cache Plugins ------------------------------------ * The :class:`.CacheImpl` is created on a per-:class:`.Template` basis. The class should ensure that only data for the parent :class:`.Template` is persisted or returned by the cache methods. The actual :class:`.Template` is available via the ``self.cache.template`` attribute. The ``self.cache.id`` attribute, which is essentially the unique modulename of the template, is a good value to use in order to represent a unique namespace of keys specific to the template. * Templates only use the :meth:`.CacheImpl.get_or_create()` method in an implicit fashion. The :meth:`.CacheImpl.set`, :meth:`.CacheImpl.get`, and :meth:`.CacheImpl.invalidate` methods are only used in response to direct programmatic access to the corresponding methods on the :class:`.Cache` object. * :class:`.CacheImpl` will be accessed in a multithreaded fashion if the :class:`.Template` itself is used multithreaded. Care should be taken to ensure caching implementations are threadsafe. * A library like `Dogpile `_, which is a minimal locking system derived from Beaker, can be used to help implement the :meth:`.CacheImpl.get_or_create` method in a threadsafe way that can maximize effectiveness across multiple threads as well as processes. :meth:`.CacheImpl.get_or_create` is the key method used by templates. * All arguments passed to ``**kw`` come directly from the parameters inside the ``<%def>``, ``<%block>``, or ``<%page>`` tags directly, minus the ``"cache_"`` prefix, as strings, with the exception of the argument ``cache_timeout``, which is passed to the plugin as the name ``timeout`` with the value converted to an integer. Arguments present in ``cache_args`` on :class:`.Template` or :class:`.TemplateLookup` are passed directly, but are superseded by those present in the most specific template tag. * The directory where :class:`.Template` places module files can be acquired using the accessor ``self.cache.template.module_directory``. This directory can be a good place to throw cache-related work files, underneath a prefix like ``_my_cache_work`` so that name conflicts with generated modules don't occur. API Reference ============= .. autoclass:: mako.cache.Cache :members: :show-inheritance: .. autoclass:: mako.cache.CacheImpl :members: :show-inheritance: .. autofunction:: mako.cache.register_plugin .. autoclass:: mako.ext.beaker_cache.BeakerCacheImpl :members: :show-inheritance: Mako-1.0.3/doc/build/changelog.rst0000644000076500000240000015162312613724176017514 0ustar classicstaff00000000000000========= Changelog ========= 1.0 === .. changelog:: :version: 1.0.3 :released: Tue Oct 27 2015 .. change:: :tags: bug, babel :pullreq: bitbucket:21 Fixed an issue where the Babel plugin would not handle a translation symbol that contained non-ascii characters. Pull request courtesy Roman Imankulov. .. changelog:: :version: 1.0.2 :released: Wed Aug 26 2015 .. change:: :tags: bug, installation :tickets: 249 The "universal wheel" marker is removed from setup.cfg, because our setup.py currently makes use of conditional dependencies. In :ticket:`249`, the discussion is ongoing on how to correct our setup.cfg / setup.py fully so that we can handle the per-version dependency changes while still maintaining optimal wheel settings, so this issue is not yet fully resolved. .. change:: :tags: bug, py3k :tickets: 250 Repair some calls within the ast module that no longer work on Python3.5; additionally replace the use of ``inspect.getargspec()`` under Python 3 (seems to be called from the TG plugin) to avoid deprecation warnings. .. change:: :tags: bug :pullreq: bitbucket:18 Update the Lingua translation extraction plugin to correctly handle templates mixing Python control statements (such as if, for and while) with template fragments. Pull request courtesy Laurent Daverio. .. change:: :tags: feature :tickets: 236 Added ``STOP_RENDERING`` keyword for returning/exiting from a template early, which is a synonym for an empty string ``""``. Previously, the docs suggested a bare ``return``, but this could cause ``None`` to appear in the rendered template result. .. seealso:: :ref:`syntax_exiting_early` .. changelog:: :version: 1.0.1 :released: Thu Jan 22 2015 .. change:: :tags: feature :pullreq: bitbucket:9 Added support for Lingua, a translation extraction system as an alternative to Babel. Pull request courtesy Wichert Akkerman. .. change:: :tags: bug, py3k :pullreq: bitbucket:11 Modernized the examples/wsgi/run_wsgi.py file for Py3k. Pull requset courtesy Cody Taylor. .. changelog:: :version: 1.0.0 :released: Sun Jun 8 2014 .. change:: :tags: bug, py2k :pullreq: bitbucket:8 Improved the error re-raise operation when a custom :paramref:`.Template.error_handler` is used that does not handle the exception; the original stack trace etc. is now preserved. Pull request courtesy Manfred Haltner. .. change:: :tags: bug, py2k, filters :pullreq: bitbucket:7 Added an html_escape filter that works in "non unicode" mode. Previously, when using ``disable_unicode=True``, the ``u`` filter would fail to handle non-ASCII bytes properly. Pull request courtesy George Xie. .. change:: :tags: general Compatibility changes; in order to modernize the codebase, Mako is now dropping support for Python 2.4 and Python 2.5 altogether. The source base is now targeted at Python 2.6 and forwards. .. change:: :tags: feature Template modules now generate a JSON "metadata" structure at the bottom of the source file which includes parseable information about the templates' source file, encoding etc. as well as a mapping of module source lines to template lines, thus replacing the "# SOURCE LINE" markers throughout the source code. The structure also indicates those lines that are explicitly not part of the template's source; the goal here is to allow better integration with coverage and other tools. .. change:: :tags: bug, py3k Fixed bug in ``decode.`` filter where a non-string object would not be correctly interpreted in Python 3. .. change:: :tags: bug, py3k :tickets: 227 Fixed bug in Python parsing logic which would fail on Python 3 when a "try/except" targeted a tuple of exception types, rather than a single exception. .. change:: :tags: feature :pullreq: bitbucket:5 mako-render is now implemented as a setuptools entrypoint script; a standalone mako.cmd.cmdline() callable is now available, and the system also uses argparse now instead of optparse. Pull request courtesy Derek Harland. .. change:: :tags: feature :pullreq: bitbucket:4 The mako-render script will now catch exceptions and run them into the text error handler, and exit with a non-zero exit code. Pull request courtesy Derek Harland. .. change:: :tags: bug :pullreq: bitbucket:2 A rework of the mako-render script allows the script to run correctly when given a file pathname that is outside of the current directory, e.g. ``mako-render ../some_template.mako``. In this case, the "template root" defaults to the directory in which the template is located, instead of ".". The script also accepts a new argument ``--template-dir`` which can be specified multiple times to establish template lookup directories. Standard input for templates also works now too. Pull request courtesy Derek Harland. .. change:: :tags: feature, py3k :pullreq: github:7 Support is added for Python 3 "keyword only" arguments, as used in defs. Pull request courtesy Eevee. 0.9 === .. changelog:: :version: 0.9.1 :released: Thu Dec 26 2013 .. change:: :tags: bug :tickets: 225 Fixed bug in Babel plugin where translator comments would be lost if intervening text nodes were encountered. Fix courtesy Ned Batchelder. .. change:: :tags: bug :tickets: Fixed TGPlugin.render method to support unicode template names in Py2K - courtesy Vladimir Magamedov. .. change:: :tags: bug :tickets: Fixed an AST issue that was preventing correct operation under alpha versions of Python 3.4. Pullreq courtesy Zer0-. .. change:: :tags: bug :tickets: Changed the format of the "source encoding" header output by the code generator to use the format ``# -*- coding:%s -*-`` instead of ``# -*- encoding:%s -*-``; the former is more common and compatible with emacs. Courtesy Martin Geisler. .. change:: :tags: bug :tickets: 224 Fixed issue where an old lexer rule prevented a template line which looked like "#*" from being correctly parsed. .. changelog:: :version: 0.9.0 :released: Tue Aug 27 2013 .. change:: :tags: bug :tickets: 219 The Context.locals_() method becomes a private underscored method, as this method has a specific internal use. The purpose of Context.kwargs has been clarified, in that it only delivers top level keyword arguments originally passed to template.render(). .. change:: :tags: bug :tickets: Fixed the babel plugin to properly interpret ${} sections inside of a "call" tag, i.e. <%self:some_tag attr="${_('foo')}"/>. Code that's subject to babel escapes in here needs to be specified as a Python expression, not a literal. This change is backwards incompatible vs. code that is relying upon a _('') translation to be working within a call tag. .. change:: :tags: bug :tickets: 187 The Babel plugin has been repaired to work on Python 3. .. change:: :tags: bug :tickets: 207 Using <%namespace import="*" module="somemodule"/> now skips over module elements that are not explcitly callable, avoiding TypeError when trying to produce partials. .. change:: :tags: bug :tickets: 190 Fixed Py3K bug where a "lambda" expression was not interpreted correctly within a template tag; also fixed in Py2.4. 0.8 === .. changelog:: :version: 0.8.1 :released: Fri May 24 2013 .. change:: :tags: bug :tickets: 216 Changed setup.py to skip installing markupsafe if Python version is < 2.6 or is between 3.0 and less than 3.3, as Markupsafe now only supports 2.6->2.X, 3.3->3.X. .. change:: :tags: bug :tickets: 214 Fixed regression where "entity" filter wasn't converted for py3k properly (added tests.) .. change:: :tags: bug :tickets: 212 Fixed bug where mako-render script wasn't compatible with Py3k. .. change:: :tags: bug :tickets: 213 Cleaned up all the various deprecation/ file warnings when running the tests under various Pythons with warnings turned on. .. changelog:: :version: 0.8.0 :released: Wed Apr 10 2013 .. change:: :tags: feature :tickets: Performance improvement to the "legacy" HTML escape feature, used for XML escaping and when markupsafe isn't present, courtesy George Xie. .. change:: :tags: bug :tickets: 209 Fixed bug whereby an exception in Python 3 against a module compiled to the filesystem would fail trying to produce a RichTraceback due to the content being in bytes. .. change:: :tags: bug :tickets: 208 Change default for compile()->reserved_names from tuple to frozenset, as this is expected to be a set by default. .. change:: :tags: feature :tickets: Code has been reworked to support Python 2.4-> Python 3.xx in place. 2to3 no longer needed. .. change:: :tags: feature :tickets: Added lexer_cls argument to Template, TemplateLookup, allows alternate Lexer classes to be used. .. change:: :tags: feature :tickets: Added future_imports parameter to Template and TemplateLookup, renders the __future__ header with desired capabilities at the top of the generated template module. Courtesy Ben Trofatter. 0.7 === .. changelog:: :version: 0.7.3 :released: Wed Nov 7 2012 .. change:: :tags: bug :tickets: legacy_html_escape function, used when Markupsafe isn't installed, was using an inline-compiled regexp which causes major slowdowns on Python 3.3; is now precompiled. .. change:: :tags: bug :tickets: 201 AST supporting now supports tuple-packed function arguments inside pure-python def or lambda expressions. .. change:: :tags: bug :tickets: Fixed Py3K bug in the Babel extension. .. change:: :tags: bug :tickets: Fixed the "filter" attribute of the <%text> tag so that it pulls locally specified identifiers from the context the same way as that of <%block> and <%filter>. .. change:: :tags: bug :tickets: Fixed bug in plugin loader to correctly raise exception when non-existent plugin is specified. .. changelog:: :version: 0.7.2 :released: Fri Jul 20 2012 .. change:: :tags: bug :tickets: 193 Fixed regression in 0.7.1 where AST parsing for Py2.4 was broken. .. changelog:: :version: 0.7.1 :released: Sun Jul 8 2012 .. change:: :tags: feature :tickets: 146 Control lines with no bodies will now succeed, as "pass" is added for these when no statements are otherwise present. Courtesy Ben Trofatter .. change:: :tags: bug :tickets: 192 Fixed some long-broken scoping behavior involving variables declared in defs and such, which only became apparent when the strict_undefined flag was turned on. .. change:: :tags: bug :tickets: 191 Can now use strict_undefined at the same time args passed to def() are used by other elements of the <%def> tag. .. changelog:: :version: 0.7.0 :released: Fri Mar 30 2012 .. change:: :tags: feature :tickets: 125 Added new "loop" variable to templates, is provided within a % for block to provide info about the loop such as index, first/last, odd/even, etc. A migration path is also provided for legacy templates via the "enable_loop" argument available on Template, TemplateLookup, and <%page>. Thanks to Ben Trofatter for all the work on this .. change:: :tags: feature :tickets: Added a real check for "reserved" names, that is names which are never pulled from the context and cannot be passed to the template.render() method. Current names are "context", "loop", "UNDEFINED". .. change:: :tags: feature :tickets: 95 The html_error_template() will now apply Pygments highlighting to the source code displayed in the traceback, if Pygments if available. Courtesy Ben Trofatter .. change:: :tags: feature :tickets: 147 Added support for context managers, i.e. "% with x as e:/ % endwith" support. Courtesy Ben Trofatter .. change:: :tags: feature :tickets: 185 Added class-level flag to CacheImpl "pass_context"; when True, the keyword argument 'context' will be passed to get_or_create() containing the Mako Context object. .. change:: :tags: bug :tickets: 182 Fixed some Py3K resource warnings due to filehandles being implicitly closed. .. change:: :tags: bug :tickets: 186 Fixed endless recursion bug when nesting multiple def-calls with content. Thanks to Jeff Dairiki. .. change:: :tags: feature :tickets: Added Jinja2 to the example benchmark suite, courtesy Vincent Férotin Older Versions ============== .. changelog:: :version: 0.6.2 :released: Thu Feb 2 2012 .. change:: :tags: bug :tickets: 86, 20 The ${{"foo":"bar"}} parsing issue is fixed!! The legendary Eevee has slain the dragon!. Also fixes quoting issue at. .. changelog:: :version: 0.6.1 :released: Sat Jan 28 2012 .. change:: :tags: bug :tickets: Added special compatibility for the 0.5.0 Cache() constructor, which was preventing file version checks and not allowing Mako 0.6 to recompile the module files. .. changelog:: :version: 0.6.0 :released: Sat Jan 21 2012 .. change:: :tags: feature :tickets: Template caching has been converted into a plugin system, whereby the usage of Beaker is just the default plugin. Template and TemplateLookup now accept a string "cache_impl" parameter which refers to the name of a cache plugin, defaulting to the name 'beaker'. New plugins can be registered as pkg_resources entrypoints under the group "mako.cache", or registered directly using mako.cache.register_plugin(). The core plugin is the mako.cache.CacheImpl class. .. change:: :tags: feature :tickets: Added support for Beaker cache regions in templates. Usage of regions should be considered as superseding the very obsolete idea of passing in backend options, timeouts, etc. within templates. .. change:: :tags: feature :tickets: The 'put' method on Cache is now 'set'. 'put' is there for backwards compatibility. .. change:: :tags: feature :tickets: The <%def>, <%block> and <%page> tags now accept any argument named "cache_*", and the key minus the "cache_" prefix will be passed as keyword arguments to the CacheImpl methods. .. change:: :tags: feature :tickets: Template and TemplateLookup now accept an argument cache_args, which refers to a dictionary containing cache parameters. The cache_dir, cache_url, cache_type, cache_timeout arguments are deprecated (will probably never be removed, however) and can be passed now as cache_args={'url':, 'type':'memcached', 'timeout':50, 'dir':'/path/to/some/directory'} .. change:: :tags: feature/bug :tickets: 180 Can now refer to context variables within extra arguments to <%block>, <%def>, i.e. <%block name="foo" cache_key="${somekey}">. Filters can also be used in this way, i.e. <%def name="foo()" filter="myfilter"> then template.render(myfilter=some_callable) .. change:: :tags: feature :tickets: 178 Added "--var name=value" option to the mako-render script, allows passing of kw to the template from the command line. .. change:: :tags: feature :tickets: 181 Added module_writer argument to Template, TemplateLookup, allows a callable to be passed which takes over the writing of the template's module source file, so that special environment-specific steps can be taken. .. change:: :tags: bug :tickets: 142 The exception message in the html_error_template is now escaped with the HTML filter. .. change:: :tags: bug :tickets: 173 Added "white-space:pre" style to html_error_template() for code blocks so that indentation is preserved .. change:: :tags: bug :tickets: 175 The "benchmark" example is now Python 3 compatible (even though several of those old template libs aren't available on Py3K, so YMMV) .. changelog:: :version: 0.5.0 :released: Wed Sep 28 2011 .. change:: :tags: :tickets: 174 A Template is explicitly disallowed from having a url that normalizes to relative outside of the root. That is, if the Lookup is based at /home/mytemplates, an include that would place the ultimate template at /home/mytemplates/../some_other_directory, i.e. outside of /home/mytemplates, is disallowed. This usage was never intended despite the lack of an explicit check. The main issue this causes is that module files can be written outside of the module root (or raise an error, if file perms aren't set up), and can also lead to the same template being cached in the lookup under multiple, relative roots. TemplateLookup instead has always supported multiple file roots for this purpose. .. changelog:: :version: 0.4.2 :released: Fri Aug 5 2011 .. change:: :tags: :tickets: 170 Fixed bug regarding <%call>/def calls w/ content whereby the identity of the "caller" callable inside the <%def> would be corrupted by the presence of another <%call> in the same block. .. change:: :tags: :tickets: 169 Fixed the babel plugin to accommodate <%block> .. changelog:: :version: 0.4.1 :released: Wed Apr 6 2011 .. change:: :tags: :tickets: 164 New tag: <%block>. A variant on <%def> that evaluates its contents in-place. Can be named or anonymous, the named version is intended for inheritance layouts where any given section can be surrounded by the <%block> tag in order for it to become overrideable by inheriting templates, without the need to specify a top-level <%def> plus explicit call. Modified scoping and argument rules as well as a more strictly enforced usage scheme make it ideal for this purpose without at all replacing most other things that defs are still good for. Lots of new docs. .. change:: :tags: :tickets: 165 a slight adjustment to the "highlight" logic for generating template bound stacktraces. Will stick to known template source lines without any extra guessing. .. changelog:: :version: 0.4.0 :released: Sun Mar 6 2011 .. change:: :tags: :tickets: A 20% speedup for a basic two-page inheritance setup rendering a table of escaped data (see http://techspot.zzzeek.org/2010/11/19/quick-mako-vs.-jinja-speed-test/). A few configurational changes which affect those in the I-don't-do-unicode camp should be noted below. .. change:: :tags: :tickets: The FastEncodingBuffer is now used by default instead of cStringIO or StringIO, regardless of whether output_encoding is set to None or not. FEB is faster than both. Only StringIO allows bytestrings of unknown encoding to pass right through, however - while it is of course not recommended to send bytestrings of unknown encoding to the output stream, this mode of usage can be re-enabled by setting the flag bytestring_passthrough to True. .. change:: :tags: :tickets: disable_unicode mode requires that output_encoding be set to None - it also forces the bytestring_passthrough flag to True. .. change:: :tags: :tickets: 156 the <%namespace> tag raises an error if the 'template' and 'module' attributes are specified at the same time in one tag. A different class is used for each case which allows a reduction in runtime conditional logic and function call overhead. .. change:: :tags: :tickets: 159 the keys() in the Context, as well as it's internal _data dictionary, now include just what was specified to render() as well as Mako builtins 'caller', 'capture'. The contents of __builtin__ are no longer copied. Thanks to Daniel Lopez for pointing this out. .. changelog:: :version: 0.3.6 :released: Sat Nov 13 2010 .. change:: :tags: :tickets: 126 Documentation is on Sphinx. .. change:: :tags: :tickets: 154 Beaker is now part of "extras" in setup.py instead of "install_requires". This to produce a lighter weight install for those who don't use the caching as well as to conform to Pyramid deployment practices. .. change:: :tags: :tickets: 153 The Beaker import (or attempt thereof) is delayed until actually needed; this to remove the performance penalty from startup, particularly for "single execution" environments such as shell scripts. .. change:: :tags: :tickets: 155 Patch to lexer to not generate an empty '' write in the case of backslash-ended lines. .. change:: :tags: :tickets: 148 Fixed missing **extra collection in setup.py which prevented setup.py from running 2to3 on install. .. change:: :tags: :tickets: New flag on Template, TemplateLookup - strict_undefined=True, will cause variables not found in the context to raise a NameError immediately, instead of defaulting to the UNDEFINED value. .. change:: :tags: :tickets: The range of Python identifiers that are considered "undefined", meaning they are pulled from the context, has been trimmed back to not include variables declared inside of expressions (i.e. from list comprehensions), as well as in the argument list of lambdas. This to better support the strict_undefined feature. The change should be fully backwards-compatible but involved a little bit of tinkering in the AST code, which hadn't really been touched for a couple of years, just FYI. .. changelog:: :version: 0.3.5 :released: Sun Oct 24 2010 .. change:: :tags: :tickets: 141 The <%namespace> tag allows expressions for the `file` argument, i.e. with ${}. The `context` variable, if needed, must be referenced explicitly. .. change:: :tags: :tickets: ${} expressions embedded in tags, such as <%foo:bar x="${...}">, now allow multiline Python expressions. .. change:: :tags: :tickets: Fixed previously non-covered regular expression, such that using a ${} expression inside of a tag element that doesn't allow them raises a CompileException instead of silently failing. .. change:: :tags: :tickets: 151 Added a try/except around "import markupsafe". This to support GAE which can't run markupsafe. No idea whatsoever if the install_requires in setup.py also breaks GAE, couldn't get an answer on this. .. changelog:: :version: 0.3.4 :released: Tue Jun 22 2010 .. change:: :tags: :tickets: Now using MarkupSafe for HTML escaping, i.e. in place of cgi.escape(). Faster C-based implementation and also escapes single quotes for additional security. Supports the __html__ attribute for the given expression as well. When using "disable_unicode" mode, a pure Python HTML escaper function is used which also quotes single quotes. Note that Pylons by default doesn't use Mako's filter - check your environment.py file. .. change:: :tags: :tickets: 137 Fixed call to "unicode.strip" in exceptions.text_error_template which is not Py3k compatible. .. changelog:: :version: 0.3.3 :released: Mon May 31 2010 .. change:: :tags: :tickets: 135 Added conditional to RichTraceback such that if no traceback is passed and sys.exc_info() has been reset, the formatter just returns blank for the "traceback" portion. .. change:: :tags: :tickets: 131 Fixed sometimes incorrect usage of exc.__class__.__name__ in html/text error templates when using Python 2.4 .. change:: :tags: :tickets: Fixed broken @property decorator on template.last_modified .. change:: :tags: :tickets: 132 Fixed error formatting when a stacktrace line contains no line number, as in when inside an eval/exec-generated function. .. change:: :tags: :tickets: When a .py is being created, the tempfile where the source is stored temporarily is now made in the same directory as that of the .py file. This ensures that the two files share the same filesystem, thus avoiding cross-filesystem synchronization issues. Thanks to Charles Cazabon. .. changelog:: :version: 0.3.2 :released: Thu Mar 11 2010 .. change:: :tags: :tickets: 116 Calling a def from the top, via template.get_def(...).render() now checks the argument signature the same way as it did in 0.2.5, so that TypeError is not raised. reopen of .. changelog:: :version: 0.3.1 :released: Sun Mar 7 2010 .. change:: :tags: :tickets: 129 Fixed incorrect dir name in setup.py .. changelog:: :version: 0.3.0 :released: Fri Mar 5 2010 .. change:: :tags: :tickets: 123 Python 2.3 support is dropped. .. change:: :tags: :tickets: 119 Python 3 support is added ! See README.py3k for installation and testing notes. .. change:: :tags: :tickets: 127 Unit tests now run with nose. .. change:: :tags: :tickets: 99 Source code escaping has been simplified. In particular, module source files are now generated with the Python "magic encoding comment", and source code is passed through mostly unescaped, except for that code which is regenerated from parsed Python source. This fixes usage of unicode in <%namespace:defname> tags. .. change:: :tags: :tickets: 122 RichTraceback(), html_error_template().render(), text_error_template().render() now accept "error" and "traceback" as optional arguments, and these are now actually used. .. change:: :tags: :tickets: The exception output generated when format_exceptions=True will now be as a Python unicode if it occurred during render_unicode(), or an encoded string if during render(). .. change:: :tags: :tickets: 112 A percent sign can be emitted as the first non-whitespace character on a line by escaping it as in "%%". .. change:: :tags: :tickets: 94 Template accepts empty control structure, i.e. % if: %endif, etc. .. change:: :tags: :tickets: 116 The <%page args> tag can now be used in a base inheriting template - the full set of render() arguments are passed down through the inherits chain. Undeclared arguments go into **pageargs as usual. .. change:: :tags: :tickets: 109 defs declared within a <%namespace> section, an uncommon feature, have been improved. The defs no longer get doubly-rendered in the body() scope, and now allow local variable assignment without breakage. .. change:: :tags: :tickets: 128 Windows paths are handled correctly if a Template is passed only an absolute filename (i.e. with c: drive etc.) and no URI - the URI is converted to a forward-slash path and module_directory is treated as a windows path. .. change:: :tags: :tickets: 73 TemplateLookup raises TopLevelLookupException for a given path that is a directory, not a filename, instead of passing through to the template to generate IOError. .. changelog:: :version: 0.2.6 :released: .. change:: :tags: :tickets: Fix mako function decorators to preserve the original function's name in all cases. Patch from Scott Torborg. .. change:: :tags: :tickets: 118 Support the <%namespacename:defname> syntax in the babel extractor. .. change:: :tags: :tickets: 88 Further fixes to unicode handling of .py files with the html_error_template. .. changelog:: :version: 0.2.5 :released: Mon Sep 7 2009 .. change:: :tags: :tickets: Added a "decorator" kw argument to <%def>, allows custom decoration functions to wrap rendering callables. Mainly intended for custom caching algorithms, not sure what other uses there may be (but there may be). Examples are in the "filtering" docs. .. change:: :tags: :tickets: 101 When Mako creates subdirectories in which to store templates, it uses the more permissive mode of 0775 instead of 0750, helping out with certain multi-process scenarios. Note that the mode is always subject to the restrictions of the existing umask. .. change:: :tags: :tickets: 104 Fixed namespace.__getattr__() to raise AttributeError on attribute not found instead of RuntimeError. .. change:: :tags: :tickets: 97 Added last_modified accessor to Template, returns the time.time() when the module was created. .. change:: :tags: :tickets: 102 Fixed lexing support for whitespace around '=' sign in defs. .. change:: :tags: :tickets: 108 Removed errant "lower()" in the lexer which was causing tags to compile with case-insensitive names, thus messing up custom <%call> names. .. change:: :tags: :tickets: 110 added "mako.__version__" attribute to the base module. .. changelog:: :version: 0.2.4 :released: Tue Dec 23 2008 .. change:: :tags: :tickets: Fixed compatibility with Jython 2.5b1. .. changelog:: :version: 0.2.3 :released: Sun Nov 23 2008 .. change:: :tags: :tickets: the <%namespacename:defname> syntax described at http://techspot.zzzeek.org/?p=28 has now been added as a built in syntax, and is recommended as a more modern syntax versus <%call expr="expression">. The %call tag itself will always remain, with <%namespacename:defname> presenting a more HTML-like alternative to calling defs, both plain and nested. Many examples of the new syntax are in the "Calling a def with embedded content" section of the docs. .. change:: :tags: :tickets: added support for Jython 2.5. .. change:: :tags: :tickets: cache module now uses Beaker's CacheManager object directly, so that all cache types are included. memcached is available as both "ext:memcached" and "memcached", the latter for backwards compatibility. .. change:: :tags: :tickets: added "cache" accessor to Template, Namespace. e.g. ${local.cache.get('somekey')} or template.cache.invalidate_body() .. change:: :tags: :tickets: added "cache_enabled=True" flag to Template, TemplateLookup. Setting this to False causes cache operations to "pass through" and execute every time; this flag should be integrated in Pylons with its own cache_enabled configuration setting. .. change:: :tags: :tickets: 92 the Cache object now supports invalidate_def(name), invalidate_body(), invalidate_closure(name), invalidate(key), which will remove the given key from the cache, if it exists. The cache arguments (i.e. storage type) are derived from whatever has been already persisted for that template. .. change:: :tags: :tickets: For cache changes to work fully, Beaker 1.1 is required. 1.0.1 and up will work as well with the exception of cache expiry. Note that Beaker 1.1 is **required** for applications which use dynamically generated keys, since previous versions will permanently store state in memory for each individual key, thus consuming all available memory for an arbitrarily large number of distinct keys. .. change:: :tags: :tickets: 93 fixed bug whereby an <%included> template with <%page> args named the same as a __builtin__ would not honor the default value specified in <%page> .. change:: :tags: :tickets: 88 fixed the html_error_template not handling tracebacks from normal .py files with a magic encoding comment .. change:: :tags: :tickets: RichTraceback() now accepts an optional traceback object to be used in place of sys.exc_info()[2]. html_error_template() and text_error_template() accept an optional render()-time argument "traceback" which is passed to the RichTraceback object. .. change:: :tags: :tickets: added ModuleTemplate class, which allows the construction of a Template given a Python module generated by a previous Template. This allows Python modules alone to be used as templates with no compilation step. Source code and template source are optional but allow error reporting to work correctly. .. change:: :tags: :tickets: 90 fixed Python 2.3 compat. in mako.pyparser .. change:: :tags: :tickets: fix Babel 0.9.3 compatibility; stripping comment tags is now optional (and enabled by default). .. changelog:: :version: 0.2.2 :released: Mon Jun 23 2008 .. change:: :tags: :tickets: 87 cached blocks now use the current context when rendering an expired section, instead of the original context passed in .. change:: :tags: :tickets: fixed a critical issue regarding caching, whereby a cached block would raise an error when called within a cache-refresh operation that was initiated after the initiating template had completed rendering. .. changelog:: :version: 0.2.1 :released: Mon Jun 16 2008 .. change:: :tags: :tickets: fixed bug where 'output_encoding' parameter would prevent render_unicode() from returning a unicode object. .. change:: :tags: :tickets: bumped magic number, which forces template recompile for this version (fixes incompatible compile symbols from 0.1 series). .. change:: :tags: :tickets: added a few docs for cache options, specifically those that help with memcached. .. changelog:: :version: 0.2.0 :released: Tue Jun 3 2008 .. change:: :tags: :tickets: Speed improvements (as though we needed them, but people contributed and there you go): .. change:: :tags: :tickets: 77 added "bytestring passthru" mode, via `disable_unicode=True` argument passed to Template or TemplateLookup. All unicode-awareness and filtering is turned off, and template modules are generated with the appropriate magic encoding comment. In this mode, template expressions can only receive raw bytestrings or Unicode objects which represent straight ASCII, and render_unicode() may not be used if multibyte characters are present. When enabled, speed improvement around 10-20%. (courtesy anonymous guest) .. change:: :tags: :tickets: 76 inlined the "write" function of Context into a local template variable. This affords a 12-30% speedup in template render time. (idea courtesy same anonymous guest) .. change:: :tags: :tickets: New Features, API changes: .. change:: :tags: :tickets: 62 added "attr" accessor to namespaces. Returns attributes configured as module level attributes, i.e. within <%! %> sections. i.e.: # somefile.html <%! foo = 27 %> # some other template <%namespace name="myns" file="somefile.html"/> ${myns.attr.foo} The slight backwards incompatibility here is, you can't have namespace defs named "attr" since the "attr" descriptor will occlude it. .. change:: :tags: :tickets: 78 cache_key argument can now render arguments passed directly to the %page or %def, i.e. <%def name="foo(x)" cached="True" cache_key="${x}"/> .. change:: :tags: :tickets: some functions on Context are now private: _push_buffer(), _pop_buffer(), caller_stack._push_frame(), caller_stack._pop_frame(). .. change:: :tags: :tickets: 56, 81 added a runner script "mako-render" which renders standard input as a template to stdout .. change:: :tags: bugfixes :tickets: 83, 84 can now use most names from __builtins__ as variable names without explicit declaration (i.e. 'id', 'exception', 'range', etc.) .. change:: :tags: bugfixes :tickets: 84 can also use builtin names as local variable names (i.e. dict, locals) (came from fix for) .. change:: :tags: bugfixes :tickets: 68 fixed bug in python generation when variable names are used with identifiers like "else", "finally", etc. inside them .. change:: :tags: bugfixes :tickets: 69 fixed codegen bug which occured when using <%page> level caching, combined with an expression-based cache_key, combined with the usage of <%namespace import="*"/> - fixed lexer exceptions not cleaning up temporary files, which could lead to a maximum number of file descriptors used in the process .. change:: :tags: bugfixes :tickets: 71 fixed issue with inline format_exceptions that was producing blank exception pages when an inheriting template is present .. change:: :tags: bugfixes :tickets: format_exceptions will apply the encoding options of html_error_template() to the buffered output .. change:: :tags: bugfixes :tickets: 75 rewrote the "whitespace adjuster" function to work with more elaborate combinations of quotes and comments .. changelog:: :version: 0.1.10 :released: .. change:: :tags: :tickets: fixed propagation of 'caller' such that nested %def calls within a <%call> tag's argument list propigates 'caller' to the %call function itself (propigates to the inner calls too, this is a slight side effect which previously existed anyway) .. change:: :tags: :tickets: fixed bug where local.get_namespace() could put an incorrect "self" in the current context .. change:: :tags: :tickets: fixed another namespace bug where the namespace functions did not have access to the correct context containing their 'self' and 'parent' .. changelog:: :version: 0.1.9 :released: .. change:: :tags: :tickets: 47 filters.Decode filter can also accept a non-basestring object and will call str() + unicode() on it .. change:: :tags: :tickets: 53 comments can be placed at the end of control lines, i.e. if foo: # a comment,, thanks to Paul Colomiets .. change:: :tags: :tickets: 16 fixed expressions and page tag arguments and with embedded newlines in CRLF templates, follow up to, thanks Eric Woroshow .. change:: :tags: :tickets: 51 added an IOError catch for source file not found in RichTraceback exception reporter .. changelog:: :version: 0.1.8 :released: Tue Jun 26 2007 .. change:: :tags: :tickets: variable names declared in render methods by internal codegen prefixed by "__M_" to prevent name collisions with user code .. change:: :tags: :tickets: 45 added a Babel (http://babel.edgewall.org/) extractor entry point, allowing extraction of gettext messages directly from mako templates via Babel .. change:: :tags: :tickets: fix to turbogears plugin to work with dot-separated names (i.e. load_template('foo.bar')). also takes file extension as a keyword argument (default is 'mak'). .. change:: :tags: :tickets: 35 more tg fix: fixed, allowing string-based templates with tgplugin even if non-compatible args were sent .. changelog:: :version: 0.1.7 :released: Wed Jun 13 2007 .. change:: :tags: :tickets: one small fix to the unit tests to support python 2.3 .. change:: :tags: :tickets: a slight hack to how cache.py detects Beaker's memcached, works around unexplained import behavior observed on some python 2.3 installations .. changelog:: :version: 0.1.6 :released: Fri May 18 2007 .. change:: :tags: :tickets: caching is now supplied directly by Beaker, which has all of MyghtyUtils merged into it now. The latest Beaker (0.7.1) also fixes a bug related to how Mako was using the cache API. .. change:: :tags: :tickets: 34 fix to module_directory path generation when the path is "./" .. change:: :tags: :tickets: 35 TGPlugin passes options to string-based templates .. change:: :tags: :tickets: 28 added an explicit stack frame step to template runtime, which allows much simpler and hopefully bug-free tracking of 'caller', fixes .. change:: :tags: :tickets: if plain Python defs are used with <%call>, a decorator @runtime.supports_callable exists to ensure that the "caller" stack is properly handled for the def. .. change:: :tags: :tickets: 37 fix to RichTraceback and exception reporting to get template source code as a unicode object .. change:: :tags: :tickets: 39 html_error_template includes options "full=True", "css=True" which control generation of HTML tags, CSS .. change:: :tags: :tickets: 40 added the 'encoding_errors' parameter to Template/TemplateLookup for specifying the error handler associated with encoding to 'output_encoding' .. change:: :tags: :tickets: 37 the Template returned by html_error_template now defaults to output_encoding=sys.getdefaultencoding(), encoding_errors='htmlentityreplace' .. change:: :tags: :tickets: control lines, i.e. % lines, support backslashes to continue long lines (#32) .. change:: :tags: :tickets: fixed codegen bug when defining <%def> within <%call> within <%call> .. change:: :tags: :tickets: leading utf-8 BOM in template files is honored according to pep-0263 .. changelog:: :version: 0.1.5 :released: Sat Mar 31 2007 .. change:: :tags: :tickets: 26 AST expression generation - added in just about everything expression-wise from the AST module .. change:: :tags: :tickets: 27 AST parsing, properly detects imports of the form "import foo.bar" .. change:: :tags: :tickets: fix to lexing of <%docs> tag nested in other tags .. change:: :tags: :tickets: 29 fix to context-arguments inside of <%include> tag which broke during 0.1.4 .. change:: :tags: :tickets: added "n" filter, disables *all* filters normally applied to an expression via <%page> or default_filters (but not those within the filter) .. change:: :tags: :tickets: added buffer_filters argument, defines filters applied to the return value of buffered/cached/filtered %defs, after all filters 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 passing special attributes or objects. .. changelog:: :version: 0.1.4 :released: Sat Mar 10 2007 .. change:: :tags: :tickets: got defs-within-defs to be cacheable .. change:: :tags: :tickets: 23 fixes to code parsing/whitespace adjusting where plain python comments may contain quote characters .. change:: :tags: :tickets: fix to variable scoping for identifiers only referenced within functions .. change:: :tags: :tickets: added a path normalization step to lookup so URIs like "/foo/bar/../etc/../foo" pre-process the ".." tokens before checking the filesystem .. change:: :tags: :tickets: fixed/improved "caller" semantics so that undefined caller is "UNDEFINED", propigates __nonzero__ method so it evaulates to False if not present, True otherwise. this way you can say % if caller:\n ${caller.body()}\n% endif .. change:: :tags: :tickets: <%include> has an "args" attribute that can pass arguments to the called template (keyword arguments only, must be declared in that page's <%page> tag.) .. change:: :tags: :tickets: <%include> plus arguments is also programmatically available via self.include_file(, **kwargs) .. change:: :tags: :tickets: 24 further escaping added for multibyte expressions in %def, %call attributes .. changelog:: :version: 0.1.3 :released: Wed Feb 21 2007 .. change:: :tags: :tickets: ***Small Syntax Change*** - the single line comment character is now *two* hash signs, i.e. "## this is a comment". This avoids a common collection with CSS selectors. .. change:: :tags: :tickets: the magic "coding" comment (i.e. # coding:utf-8) will still work with either one "#" sign or two for now; two is preferred going forward, i.e. ## coding:. .. change:: :tags: :tickets: new multiline comment form: "<%doc> a comment " .. change:: :tags: :tickets: UNDEFINED evaluates to False .. change:: :tags: :tickets: improvement to scoping of "caller" variable when using <%call> tag .. change:: :tags: :tickets: added lexer error for unclosed control-line (%) line .. change:: :tags: :tickets: added "preprocessor" argument to Template, TemplateLookup - is a single callable or list of callables which will be applied to the template text before lexing. given the text as an argument, returns the new text. .. change:: :tags: :tickets: added mako.ext.preprocessors package, contains one preprocessor so far: 'convert_comments', which will convert single # comments to the new ## format .. changelog:: :version: 0.1.2 :released: Thu Feb 1 2007 .. change:: :tags: :tickets: 11 fix to parsing of code/expression blocks to insure that non-ascii characters, combined with a template that indicates a non-standard encoding, are expanded into backslash-escaped glyphs before being AST parsed .. change:: :tags: :tickets: all template lexing converts the template to unicode first, to immediately catch any encoding issues and ensure internal unicode representation. .. change:: :tags: :tickets: added module_filename argument to Template to allow specification of a specific module file .. change:: :tags: :tickets: 14 added modulename_callable to TemplateLookup to allow a function to determine module filenames (takes filename, uri arguments). used for .. change:: :tags: :tickets: added optional input_encoding flag to Template, to allow sending a unicode() object with no magic encoding comment .. change:: :tags: :tickets: "expression_filter" argument in <%page> applies only to expressions .. change:: :tags: "unicode" :tickets: added "default_filters" argument to Template, TemplateLookup. applies only to expressions, gets prepended to "expression_filter" arg from <%page>. defaults to, so that all expressions get stringified into u'' by default (this is what Mako already does). By setting to [], expressions are passed through raw. .. change:: :tags: :tickets: added "imports" argument to Template, TemplateLookup. so you can predefine a list of import statements at the top of the template. can be used in conjunction with default_filters. .. change:: :tags: :tickets: 16 support for CRLF templates...whoops ! welcome to all the windows users. .. change:: :tags: :tickets: small fix to local variable propigation for locals that are conditionally declared .. change:: :tags: :tickets: got "top level" def calls to work, i.e. template.get_def("somedef").render() .. changelog:: :version: 0.1.1 :released: Sun Jan 14 2007 .. change:: :tags: :tickets: 8 buffet plugin supports string-based templates, allows ToscaWidgets to work .. change:: :tags: :tickets: AST parsing fixes: fixed TryExcept identifier parsing .. change:: :tags: :tickets: removed textmate tmbundle from contrib and into separate SVN location; windows users cant handle those files, setuptools not very good at "pruning" certain directories .. change:: :tags: :tickets: fix so that "cache_timeout" parameter is propigated .. change:: :tags: :tickets: fix to expression filters so that string conversion (actually unicode) properly occurs before filtering .. change:: :tags: :tickets: better error message when a lookup is attempted with a template that has no lookup .. change:: :tags: :tickets: implemented "module" attribute for namespace .. change:: :tags: :tickets: fix to code generation to correctly track multiple defs with the same name .. change:: :tags: :tickets: 9 "directories" can be passed to TemplateLookup as a scalar in which case it gets converted to a list Mako-1.0.3/doc/build/conf.py0000644000076500000240000002242012613724132016312 0ustar classicstaff00000000000000# -*- coding: utf-8 -*- # # Mako documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) sys.path.insert(0, os.path.abspath('.')) import mako # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. #extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', # 'sphinx.ext.doctest', 'builder.builders'] extensions = ['sphinx.ext.autodoc','sphinx.ext.intersphinx', 'changelog', 'sphinx_paramlinks', 'builder.builders'] changelog_render_ticket = "https://bitbucket.org/zzzeek/mako/issue/%s/" changelog_render_pullreq = { "bitbucket": "https://bitbucket.org/zzzeek/mako/pull-request/%s", "default": "https://bitbucket.org/zzzeek/mako/pull-request/%s", "github": "https://github.com/zzzeek/mako/pull/%s", } # Add any paths that contain templates here, relative to this directory. templates_path = ['templates'] nitpicky = True site_base = "http://www.makotemplates.org" # The suffix of source filenames. source_suffix = '.rst' template_bridge = "builder.builders.MakoBridge" # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Mako' copyright = u'the Mako authors and contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = mako.__version__ # The full version, including alpha/beta/rc tags. release = mako.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". html_title = "%s %s Documentation" % (project, release) # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%m/%d/%Y %H:%M:%S' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_domain_indices = False # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, the reST sources are included in the HTML build as _sources/. #html_copy_source = True # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Makodoc' #autoclass_content = 'both' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'mako_%s.tex' % release.replace('.', '_'), ur'Mako Documentation', ur'Mike Bayer', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. # sets TOC depth to 2. latex_preamble = '\setcounter{tocdepth}{3}' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True #latex_elements = { # 'papersize': 'letterpaper', # 'pointsize': '10pt', #} # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'mako', u'Mako Documentation', [u'Mako authors'], 1) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'Mako' epub_author = u'Mako authors' epub_publisher = u'Mako authors' epub_copyright = u'Mako authors' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True intersphinx_mapping = { 'dogpilecache':('http://dogpilecache.readthedocs.org/en/latest', None), 'beaker':('http://beaker.readthedocs.org/en/latest',None), } Mako-1.0.3/doc/build/defs.rst0000644000076500000240000004245412613724132016477 0ustar classicstaff00000000000000.. _defs_toplevel: =============== Defs and Blocks =============== ``<%def>`` and ``<%block>`` are two tags that both demarcate any block of text and/or code. They both exist within generated Python as a callable function, i.e., a Python ``def``. They differ in their scope and calling semantics. Whereas ``<%def>`` provides a construct that is very much like a named Python ``def``, the ``<%block>`` is more layout oriented. Using Defs ========== The ``<%def>`` tag requires a ``name`` attribute, where the ``name`` references a Python function signature: .. sourcecode:: mako <%def name="hello()"> hello world To invoke the ``<%def>``, it is normally called as an expression: .. sourcecode:: mako the def: ${hello()} If the ``<%def>`` is not nested inside of another ``<%def>``, it's known as a **top level def** and can be accessed anywhere in the template, including above where it was defined. All defs, top level or not, have access to the current contextual namespace in exactly the same way their containing template does. Suppose the template below is executed with the variables ``username`` and ``accountdata`` inside the context: .. sourcecode:: mako Hello there ${username}, how are ya. Lets see what your account says: ${account()} <%def name="account()"> Account for ${username}:
% for row in accountdata: Value: ${row}
% endfor The ``username`` and ``accountdata`` variables are present within the main template body as well as the body of the ``account()`` def. Since defs are just Python functions, you can define and pass arguments to them as well: .. sourcecode:: mako ${account(accountname='john')} <%def name="account(accountname, type='regular')"> account name: ${accountname}, type: ${type} When you declare an argument signature for your def, they are required to follow normal Python conventions (i.e., all arguments are required except keyword arguments with a default value). This is in contrast to using context-level variables, which evaluate to ``UNDEFINED`` if you reference a name that does not exist. Calling Defs from Other Files ----------------------------- Top level ``<%def>``\ s are **exported** by your template's module, and can be called from the outside; including from other templates, as well as normal Python code. Calling a ``<%def>`` from another template is something like using an ``<%include>`` -- except you are calling a specific function within the template, not the whole template. The remote ``<%def>`` call is also a little bit like calling functions from other modules in Python. There is an "import" step to pull the names from another template into your own template; then the function or functions are available. To import another template, use the ``<%namespace>`` tag: .. sourcecode:: mako <%namespace name="mystuff" file="mystuff.html"/> The above tag adds a local variable ``mystuff`` to the current scope. Then, just call the defs off of ``mystuff``: .. sourcecode:: mako ${mystuff.somedef(x=5,y=7)} The ``<%namespace>`` tag also supports some of the other semantics of Python's ``import`` statement, including pulling names into the local variable space, or using ``*`` to represent all names, using the ``import`` attribute: .. sourcecode:: mako <%namespace file="mystuff.html" import="foo, bar"/> This is just a quick intro to the concept of a **namespace**, which is a central Mako concept that has its own chapter in these docs. For more detail and examples, see :ref:`namespaces_toplevel`. Calling Defs Programmatically ----------------------------- You can call defs programmatically from any :class:`.Template` object using the :meth:`~.Template.get_def()` method, which returns a :class:`.DefTemplate` object. This is a :class:`.Template` subclass which the parent :class:`.Template` creates, and is usable like any other template: .. sourcecode:: python from mako.template import Template template = Template(""" <%def name="hi(name)"> hi ${name}! <%def name="bye(name)"> bye ${name}! """) print(template.get_def("hi").render(name="ed")) print(template.get_def("bye").render(name="ed")) Defs within Defs ---------------- The def model follows regular Python rules for closures. Declaring ``<%def>`` inside another ``<%def>`` declares it within the parent's **enclosing scope**: .. sourcecode:: mako <%def name="mydef()"> <%def name="subdef()"> a sub def i'm the def, and the subcomponent is ${subdef()} Just like Python, names that exist outside the inner ``<%def>`` exist inside it as well: .. sourcecode:: mako <% x = 12 %> <%def name="outer()"> <% y = 15 %> <%def name="inner()"> inner, x is ${x}, y is ${y} outer, x is ${x}, y is ${y} Assigning to a name inside of a def declares that name as local to the scope of that def (again, like Python itself). This means the following code will raise an error: .. sourcecode:: mako <% x = 10 %> <%def name="somedef()"> ## error ! somedef, x is ${x} <% x = 27 %> ...because the assignment to ``x`` declares ``x`` as local to the scope of ``somedef``, rendering the "outer" version unreachable in the expression that tries to render it. .. _defs_with_content: Calling a Def with Embedded Content and/or Other Defs ----------------------------------------------------- A flip-side to def within def is a def call with content. This is where you call a def, and at the same time declare a block of content (or multiple blocks) that can be used by the def being called. The main point of such a call is to create custom, nestable tags, just like any other template language's custom-tag creation system -- where the external tag controls the execution of the nested tags and can communicate state to them. Only with Mako, you don't have to use any external Python modules, you can define arbitrarily nestable tags right in your templates. To achieve this, the target def is invoked using the form ``<%namespacename:defname>`` instead of the normal ``${}`` syntax. This syntax, introduced in Mako 0.2.3, is functionally equivalent to another tag known as ``%call``, which takes the form ``<%call expr='namespacename.defname(args)'>``. While ``%call`` is available in all versions of Mako, the newer style is probably more familiar looking. The ``namespace`` portion of the call is the name of the **namespace** in which the def is defined -- in the most simple cases, this can be ``local`` or ``self`` to reference the current template's namespace (the difference between ``local`` and ``self`` is one of inheritance -- see :ref:`namespaces_builtin` for details). When the target def is invoked, a variable ``caller`` is placed in its context which contains another namespace containing the body and other defs defined by the caller. The body itself is referenced by the method ``body()``. Below, we build a ``%def`` that operates upon ``caller.body()`` to invoke the body of the custom tag: .. sourcecode:: mako <%def name="buildtable()">
${caller.body()}
<%self:buildtable> I am the table body. This produces the output (whitespace formatted): .. sourcecode:: html
I am the table body.
Using the older ``%call`` syntax looks like: .. sourcecode:: mako <%def name="buildtable()">
${caller.body()}
<%call expr="buildtable()"> I am the table body. The ``body()`` can be executed multiple times or not at all. This means you can use def-call-with-content to build iterators, conditionals, etc: .. sourcecode:: mako <%def name="lister(count)"> % for x in range(count): ${caller.body()} % endfor <%self:lister count="${3}"> hi Produces: .. sourcecode:: html hi hi hi Notice above we pass ``3`` as a Python expression, so that it remains as an integer. A custom "conditional" tag: .. sourcecode:: mako <%def name="conditional(expression)"> % if expression: ${caller.body()} % endif <%self:conditional expression="${4==4}"> i'm the result Produces: .. sourcecode:: html i'm the result But that's not all. The ``body()`` function also can handle arguments, which will augment the local namespace of the body callable. The caller must define the arguments which it expects to receive from its target def using the ``args`` attribute, which is a comma-separated list of argument names. Below, our ``<%def>`` calls the ``body()`` of its caller, passing in an element of data from its argument: .. sourcecode:: mako <%def name="layoutdata(somedata)"> % for item in somedata: % for col in item: % endfor % endfor
${caller.body(col=col)}
<%self:layoutdata somedata="${[[1,2,3],[4,5,6],[7,8,9]]}" args="col">\ Body data: ${col}\ Produces: .. sourcecode:: html
Body data: 1 Body data: 2 Body data: 3
Body data: 4 Body data: 5 Body data: 6
Body data: 7 Body data: 8 Body data: 9
You don't have to stick to calling just the ``body()`` function. The caller can define any number of callables, allowing the ``<%call>`` tag to produce whole layouts: .. sourcecode:: mako <%def name="layout()"> ## a layout def
${caller.header()}
${caller.body()}
## calls the layout def <%self:layout> <%def name="header()"> I am the header <%def name="sidebar()">
  • sidebar 1
  • sidebar 2
this is the body The above layout would produce: .. sourcecode:: html
I am the header
this is the body
The number of things you can do with ``<%call>`` and/or the ``<%namespacename:defname>`` calling syntax is enormous. You can create form widget libraries, such as an enclosing ``
`` tag and nested HTML input elements, or portable wrapping schemes using ``
`` or other elements. You can create tags that interpret rows of data, such as from a database, providing the individual columns of each row to a ``body()`` callable which lays out the row any way it wants. Basically anything you'd do with a "custom tag" or tag library in some other system, Mako provides via ``<%def>`` tags and plain Python callables which are invoked via ``<%namespacename:defname>`` or ``<%call>``. .. _blocks: Using Blocks ============ The ``<%block>`` tag introduces some new twists on the ``<%def>`` tag which make it more closely tailored towards layout. .. versionadded:: 0.4.1 An example of a block: .. sourcecode:: mako <%block> this is a block. In the above example, we define a simple block. The block renders its content in the place that it's defined. Since the block is called for us, it doesn't need a name and the above is referred to as an **anonymous block**. So the output of the above template will be: .. sourcecode:: html this is a block. So in fact the above block has absolutely no effect. Its usefulness comes when we start using modifiers. Such as, we can apply a filter to our block: .. sourcecode:: mako <%block filter="h"> this is some escaped html. or perhaps a caching directive: .. sourcecode:: mako <%block cached="True" cache_timeout="60"> This content will be cached for 60 seconds. Blocks also work in iterations, conditionals, just like defs: .. sourcecode:: mako % if some_condition: <%block>condition is met % endif While the block renders at the point it is defined in the template, the underlying function is present in the generated Python code only once, so there's no issue with placing a block inside of a loop or similar. Anonymous blocks are defined as closures in the local rendering body, so have access to local variable scope: .. sourcecode:: mako % for i in range(1, 4): <%block>i is ${i} % endfor Using Named Blocks ------------------ Possibly the more important area where blocks are useful is when we do actually give them names. Named blocks are tailored to behave somewhat closely to Jinja2's block tag, in that they define an area of a layout which can be overridden by an inheriting template. In sharp contrast to the ``<%def>`` tag, the name given to a block is global for the entire template regardless of how deeply it's nested: .. sourcecode:: mako <%block name="header"> <%block name="title">Title</%block> ${next.body()} The above example has two named blocks "``header``" and "``title``", both of which can be referred to by an inheriting template. A detailed walkthrough of this usage can be found at :ref:`inheritance_toplevel`. Note above that named blocks don't have any argument declaration the way defs do. They still implement themselves as Python functions, however, so they can be invoked additional times beyond their initial definition: .. sourcecode:: mako
<%block name="pagecontrol"> previous page | next page ## some content
${pagecontrol()}
The content referenced by ``pagecontrol`` above will be rendered both above and below the ```` tags. To keep things sane, named blocks have restrictions that defs do not: * The ``<%block>`` declaration cannot have any argument signature. * The name of a ``<%block>`` can only be defined once in a template -- an error is raised if two blocks of the same name occur anywhere in a single template, regardless of nesting. A similar error is raised if a top level def shares the same name as that of a block. * A named ``<%block>`` cannot be defined within a ``<%def>``, or inside the body of a "call", i.e. ``<%call>`` or ``<%namespacename:defname>`` tag. Anonymous blocks can, however. Using Page Arguments in Named Blocks ------------------------------------ A named block is very much like a top level def. It has a similar restriction to these types of defs in that arguments passed to the template via the ``<%page>`` tag aren't automatically available. Using arguments with the ``<%page>`` tag is described in the section :ref:`namespaces_body`, and refers to scenarios such as when the ``body()`` method of a template is called from an inherited template passing arguments, or the template is invoked from an ``<%include>`` tag with arguments. To allow a named block to share the same arguments passed to the page, the ``args`` attribute can be used: .. sourcecode:: mako <%page args="post"/> <%block name="post_prose" args="post"> ${post.content} Where above, if the template is called via a directive like ``<%include file="post.mako" args="post=post" />``, the ``post`` variable is available both in the main body as well as the ``post_prose`` block. Similarly, the ``**pageargs`` variable is present, in named blocks only, for those arguments not explicit in the ``<%page>`` tag: .. sourcecode:: mako <%block name="post_prose"> ${pageargs['post'].content} The ``args`` attribute is only allowed with named blocks. With anonymous blocks, the Python function is always rendered in the same scope as the call itself, so anything available directly outside the anonymous block is available inside as well. Mako-1.0.3/doc/build/filtering.rst0000644000076500000240000002442512613724132017537 0ustar classicstaff00000000000000.. _filtering_toplevel: ======================= Filtering and Buffering ======================= Expression Filtering ==================== As described in the chapter :ref:`syntax_toplevel`, the "``|``" operator can be applied to a "``${}``" expression to apply escape filters to the output: .. sourcecode:: mako ${"this is some text" | u} The above expression applies URL escaping to the expression, and produces ``this+is+some+text``. The built-in escape flags are: * ``u`` : URL escaping, provided by ``urllib.quote_plus(string.encode('utf-8'))`` * ``h`` : HTML escaping, provided by ``markupsafe.escape(string)`` .. versionadded:: 0.3.4 Prior versions use ``cgi.escape(string, True)``. * ``x`` : XML escaping * ``trim`` : whitespace trimming, provided by ``string.strip()`` * ``entity`` : produces HTML entity references for applicable strings, derived from ``htmlentitydefs`` * ``unicode`` (``str`` on Python 3): produces a Python unicode string (this function is applied by default) * ``decode.``: decode input into a Python unicode with the specified encoding * ``n`` : disable all default filtering; only filters specified in the local expression tag will be applied. To apply more than one filter, separate them by a comma: .. sourcecode:: mako ${" some value " | h,trim} The above produces ``<tag>some value</tag>``, with no leading or trailing whitespace. The HTML escaping function is applied first, the "trim" function second. Naturally, you can make your own filters too. A filter is just a Python function that accepts a single string argument, and returns the filtered result. The expressions after the ``|`` operator draw upon the local namespace of the template in which they appear, meaning you can define escaping functions locally: .. sourcecode:: mako <%! def myescape(text): return "" + text + "" %> Here's some tagged text: ${"text" | myescape} Or from any Python module: .. sourcecode:: mako <%! import myfilters %> Here's some tagged text: ${"text" | myfilters.tagfilter} A page can apply a default set of filters to all expression tags using the ``expression_filter`` argument to the ``%page`` tag: .. sourcecode:: mako <%page expression_filter="h"/> Escaped text: ${"some html"} Result: .. sourcecode:: html Escaped text: <html>some html</html> .. _filtering_default_filters: The ``default_filters`` Argument -------------------------------- In addition to the ``expression_filter`` argument, the ``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 ``disable_unicode=True`` is set in which case it defaults to ``["str"]``: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=['unicode']) To replace the usual ``unicode``/``str`` function with a specific encoding, the ``decode`` filter can be substituted: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=['decode.utf8']) To disable ``default_filters`` entirely, set it to an empty list: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=[]) Any string name can be added to ``default_filters`` where it will be added to all expressions as a filter. The filters are applied from left to right, meaning the leftmost filter is applied first. .. sourcecode:: python t = Template(templatetext, default_filters=['unicode', 'myfilter']) To ease the usage of ``default_filters`` with custom filters, you can also add imports (or other code) to all templates using the ``imports`` argument: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=['unicode', 'myfilter'], imports=['from mypackage import myfilter']) The above will generate templates something like this: .. sourcecode:: python # .... from mypackage import myfilter def render_body(context): context.write(myfilter(unicode("some text"))) 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 ``<%page>`` tag as well as in ``default_filters``. Such as: .. sourcecode:: mako ${'myexpression' | n} will render ``myexpression`` with no filtering of any kind, and: .. sourcecode:: mako ${'myexpression' | n,trim} will render ``myexpression`` using the ``trim`` filter only. Filtering Defs and Blocks ========================= The ``%def`` and ``%block`` tags have an argument called ``filter`` which will apply the given list of filter functions to the output of the ``%def``: .. sourcecode:: mako <%def name="foo()" filter="h, trim"> this is bold When the ``filter`` attribute is applied to a def as above, the def is automatically **buffered** as well. This is described next. 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 :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 function is the content it produced, which is then delivered to your template just like any other expression substitution, except that normally, this is not the case; the return value of ``${somedef()}`` is simply the empty string ``''``. By the time you receive this empty string, the output of ``somedef()`` has been sent to the underlying buffer. You may not want this effect, if for example you are doing something like this: .. sourcecode:: mako ${" results " + somedef() + " more results "} If the ``somedef()`` function produced the content "``somedef's results``", the above template would produce this output: .. sourcecode:: html somedef's results results more results This is because ``somedef()`` fully executes before the expression returns the results of its concatenation; the concatenation in turn receives just the empty string as its middle expression. Mako provides two ways to work around this. One is by applying buffering to the ``%def`` itself: .. sourcecode:: mako <%def name="somedef()" buffered="True"> somedef's results The above definition will generate code similar to this: .. sourcecode:: python def somedef(): context.push_buffer() try: context.write("somedef's results") finally: buf = context.pop_buffer() return buf.getvalue() So that the content of ``somedef()`` is sent to a second buffer, 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 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 be useful for a filtering function that wishes to apply a transformation to the text as a whole. The other way to buffer the output of a def or any Mako callable is by using the built-in ``capture`` function. This function performs an operation similar to the above buffering operation except it is specified by the caller. .. sourcecode:: mako ${" results " + capture(somedef) + " more results "} Note that the first argument to the ``capture`` function is **the function itself**, not the result of calling it. This is because the ``capture`` function takes over the job of actually calling the target function, after setting up a buffered environment. To send arguments to the function, just send them to ``capture`` instead: .. sourcecode:: mako ${capture(somedef, 17, 'hi', use_paging=True)} The above call is equivalent to the unbuffered call: .. sourcecode:: mako ${somedef(17, 'hi', use_paging=True)} Decorating ========== .. versionadded:: 0.2.5 Somewhat like 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 intent of this function is to allow the creation of custom cache logic, but there may be other uses as well. ``decorator`` is intended to be used with a regular Python function, such as one defined in a library module. Here we'll illustrate the python function defined in the template for simplicities' sake: .. sourcecode:: mako <%! def bar(fn): def decorate(context, *args, **kw): context.write("BAR") fn(*args, **kw) context.write("BAR") return '' return decorate %> <%def name="foo()" decorator="bar"> this is foo ${foo()} 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 :func:`.capture` callable in the ``mako.runtime`` module (available in templates as just ``runtime``): .. sourcecode:: mako <%! def bar(fn): def decorate(context, *args, **kw): return "BAR" + runtime.capture(context, fn, *args, **kw) + "BAR" return decorate %> <%def name="foo()" decorator="bar"> this is foo ${foo()} 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 :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. Mako-1.0.3/doc/build/index.rst0000644000076500000240000000041412613724132016653 0ustar classicstaff00000000000000Table of Contents ================= .. toctree:: :maxdepth: 2 usage syntax defs runtime namespaces inheritance filtering unicode caching changelog Indices and Tables ------------------ * :ref:`genindex` * :ref:`search` Mako-1.0.3/doc/build/inheritance.rst0000644000076500000240000004642212613724132020046 0ustar classicstaff00000000000000.. _inheritance_toplevel: =========== 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. Using template inheritance, two or more templates can organize themselves into an **inheritance chain**, where content and functions from all involved templates can be intermixed. The general paradigm of template inheritance is this: if a template ``A`` inherits from template ``B``, then template ``A`` agrees to send the executional control to template ``B`` at runtime (``A`` is called the **inheriting** template). Template ``B``, the **inherited** template, then makes decisions as to what resources from ``A`` shall be executed. In practice, it looks like this. Here's a hypothetical inheriting template, ``index.html``: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%block name="header"> this is some header content this is the body content. And ``base.html``, the inherited template: .. sourcecode:: mako ## base.html
<%block name="header"/>
${self.body()} 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 :doc:`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
this is some header content
this is the body content. ...and that is template inheritance in a nutshell. The main idea is that the methods that you call upon ``self`` always correspond to the topmost definition of that method. Very much the way ``self`` works in a Python class, even though Mako is not actually using Python class inheritance to implement this functionality. (Mako doesn't take the "inheritance" metaphor too seriously; while useful to setup some commonly recognized semantics, a textual template is not very much like an object-oriented class construct in practice). Nesting Blocks ============== The named blocks defined in an inherited template can also be nested within other blocks. The name given to each block is globally accessible via any inheriting template. We can add a new block ``title`` to our ``header`` block: .. sourcecode:: mako ## base.html
<%block name="header">

<%block name="title"/>

${self.body()} The inheriting template can name either or both of ``header`` and ``title``, separately or nested themselves: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%block name="header"> this is some header content ${parent.header()} <%block name="title"> this is the title this is the body content. Note when we overrode ``header``, we added an extra call ``${parent.header()}`` in order to invoke the parent's ``header`` block in addition to our own. That's described in more detail below, in :ref:`parent_namespace`. Rendering a Named Block Multiple Times ====================================== Recall from the section :ref:`blocks` that a named block is just like a ``<%def>``, with some different usage rules. We can call one of our named sections distinctly, for example a section that is used more than once, such as the title of a page: .. sourcecode:: mako ${self.title()} <%block name="header">

<%block name="title"/>

${self.body()} Where above an inheriting template can define ``<%block name="title">`` just once, and it will be used in the base template both in the ```` section as well as the ``<h2>``. But what about Defs? ==================== The previous example used the ``<%block>`` tag to produce areas of content to be overridden. Before Mako 0.4.1, there wasn't any such tag -- instead there was only the ``<%def>`` tag. As it turns out, named blocks and defs are largely interchangeable. The def simply doesn't call itself automatically, and has more open-ended naming and scoping rules that are more flexible and similar to Python itself, but less suited towards layout. The first example from this chapter using defs would look like: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%def name="header()"> this is some header content </%def> this is the body content. And ``base.html``, the inherited template: .. sourcecode:: mako ## base.html <html> <body> <div class="header"> ${self.header()} </div> ${self.body()} <div class="footer"> ${self.footer()} </div> </body> </html> <%def name="header()"/> <%def name="footer()"> this is the footer </%def> Above, we illustrate that defs differ from blocks in that their definition and invocation are defined in two separate places, instead of at once. You can *almost* do exactly what a block does if you put the two together: .. sourcecode:: mako <div class="header"> <%def name="header()"></%def>${self.header()} </div> The ``<%block>`` is obviously more streamlined than the ``<%def>`` for this kind of usage. In addition, the above "inline" approach with ``<%def>`` does not work with nesting: .. sourcecode:: mako <head> <%def name="header()"> <title> ## this won't work ! <%def name="title()">default title</%def>${self.title()} ${self.header()} Where above, the ``title()`` def, because it's a def within a def, is not part of the template's exported namespace and will not be part of ``self``. If the inherited template did define its own ``title`` def at the top level, it would be called, but the "default title" above is not present at all on ``self`` no matter what. For this to work as expected you'd instead need to say: .. sourcecode:: mako <%def name="header()"> ${self.title()} ${self.header()} <%def name="title()"/> That is, ``title`` is defined outside of any other defs so that it is in the ``self`` namespace. It works, but the definition needs to be potentially far away from the point of render. A named block is always placed in the ``self`` namespace, regardless of nesting, so this restriction is lifted: .. sourcecode:: mako ## base.html <%block name="header"> <%block name="title"/> The above template defines ``title`` inside of ``header``, and an inheriting template can define one or both in **any** configuration, nested inside each other or not, in order for them to be used: .. sourcecode:: mako ## index.html <%inherit file="base.html"/> <%block name="title"> the title <%block name="header"> the header So while the ``<%block>`` tag lifts the restriction of nested blocks not being available externally, in order to achieve this it *adds* the restriction that all block names in a single template need 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 ======================================================== Sometimes you have an inheritance chain that spans more than two templates. Or maybe you don't, but you'd like to build your system such that extra inherited templates can be inserted in the middle of a chain where they would be smoothly integrated. If each template wants to define its layout just within its main body, you can't just call ``self.body()`` to get at the inheriting template's body, since that is only the topmost body. To get at the body of the *next* template, you call upon the namespace ``next``, which is the namespace of the template **immediately following** the current template. Lets change the line in ``base.html`` which calls upon ``self.body()`` to instead call upon ``next.body()``: .. sourcecode:: mako ## base.html
<%block name="header"/>
${next.body()} Lets also add an intermediate template called ``layout.html``, which inherits from ``base.html``: .. sourcecode:: mako ## layout.html <%inherit file="base.html"/>
    <%block name="toolbar">
  • selection 1
  • selection 2
  • selection 3
${next.body()}
And finally change ``index.html`` to inherit from ``layout.html`` instead: .. sourcecode:: mako ## index.html <%inherit file="layout.html"/> ## .. rest of template In this setup, each call to ``next.body()`` will render the body of the next template in the inheritance chain (which can be written as ``base.html -> layout.html -> index.html``). Control is still first passed to the bottommost template ``base.html``, and ``self`` still references the topmost definition of any particular def. The output we get would be: .. sourcecode:: html
this is some header content
  • selection 1
  • selection 2
  • selection 3
this is the body content.
So above, we have the ````, ```` and ``header``/``footer`` layout of ``base.html``, we have the ``
    `` and ``mainlayout`` section of ``layout.html``, and the main body of ``index.html`` as well as its overridden ``header`` def. The ``layout.html`` template is inserted into the middle of the chain without ``base.html`` having to change anything. Without the ``next`` namespace, only the main body of ``index.html`` could be used; there would be no way to call ``layout.html``'s body content. .. _parent_namespace: 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 namespace of the template **immediately preceding** the current template. What's useful about this namespace is that defs or blocks can call upon their overridden versions. This is not as hard as it sounds and is very much like using the ``super`` keyword in Python. Lets modify ``index.html`` to augment the list of selections provided by the ``toolbar`` function in ``layout.html``: .. sourcecode:: mako ## index.html <%inherit file="layout.html"/> <%block name="header"> this is some header content <%block name="toolbar"> ## call the parent's toolbar first ${parent.toolbar()}
  • selection 4
  • selection 5
  • this is the body content. Above, we implemented a ``toolbar()`` function, which is meant to override the definition of ``toolbar`` within the inherited template ``layout.html``. However, since we want the content from that of ``layout.html`` as well, we call it via the ``parent`` namespace whenever we want it's content, in this case before we add our own selections. So the output for the whole thing is now: .. sourcecode:: html
    this is some header content
    • selection 1
    • selection 2
    • selection 3
    • selection 4
    • selection 5
    this is the body content.
    and you're now a template inheritance ninja! Using ``<%include>`` with Template Inheritance ============================================== A common source of confusion is the behavior of the ``<%include>`` tag, often in conjunction with its interaction within template inheritance. Key to understanding the ``<%include>`` tag is that it is a *dynamic*, e.g. runtime, include, and not a static include. The ``<%include>`` is only processed as the template renders, and not at inheritance setup time. When encountered, the referenced template is run fully as an entirely separate template with no linkage to any current inheritance structure. If the tag were on the other hand a *static* include, this would allow source within the included template to interact within the same inheritance context as the calling template, but currently Mako has no static include facility. In practice, this means that ``<%block>`` elements defined in an ``<%include>`` file will not interact with corresponding ``<%block>`` elements in the calling template. A common mistake is along these lines: .. sourcecode:: mako ## partials.mako <%block name="header"> Global Header ## parent.mako <%include file="partials.mako"> ## child.mako <%inherit file="parent.mako"> <%block name="header"> Custom Header Above, one might expect that the ``"header"`` block declared in ``child.mako`` might be invoked, as a result of it overriding the same block present in ``parent.mako`` via the include for ``partials.mako``. But this is not the case. Instead, ``parent.mako`` will invoke ``partials.mako``, which then invokes ``"header"`` in ``partials.mako``, and then is finished rendering. Nothing from ``child.mako`` will render; there is no interaction between the ``"header"`` block in ``child.mako`` and the ``"header"`` block in ``partials.mako``. Instead, ``parent.mako`` must explicitly state the inheritance structure. In order to call upon specific elements of ``partials.mako``, we will call upon it as a namespace: .. sourcecode:: mako ## partials.mako <%block name="header"> Global Header ## parent.mako <%namespace name="partials" file="partials.mako"/> <%block name="header"> ${partials.header()} ## child.mako <%inherit file="parent.mako"> <%block name="header"> Custom Header Where above, ``parent.mako`` states the inheritance structure that ``child.mako`` is to participate within. ``partials.mako`` only defines defs/blocks that can be used on a per-name basis. Another scenario is below, which results in both ``"SectionA"`` blocks being rendered for the ``child.mako`` document: .. sourcecode:: mako ## base.mako ${self.body()} <%block name="SectionA"> base.mako ## parent.mako <%inherit file="base.mako"> <%include file="child.mako"> ## child.mako <%block name="SectionA"> child.mako The resolution is similar; instead of using ``<%include>``, we call upon the blocks of ``child.mako`` using a namespace: .. sourcecode:: mako ## parent.mako <%inherit file="base.mako"> <%namespace name="child" file="child.mako"> <%block name="SectionA"> ${child.SectionA()} .. _inheritance_attr: Inheritable Attributes ====================== 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: .. sourcecode:: mako <%! class_ = "grey" %>
    ${self.body()}
    If an inheriting template overrides ``class_`` to be ``"white"``, as in: .. sourcecode:: mako <%! class_ = "white" %> <%inherit file="parent.html"/> This is the body you'll get output like: .. sourcecode:: html
    This is the body
    .. seealso:: :ref:`namespace_attr_for_includes` - a more sophisticated example using :attr:`.Namespace.attr`. Mako-1.0.3/doc/build/Makefile0000644000076500000240000001137412613724132016461 0ustar classicstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = output # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest dist-html site-mako help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dist-html same as html, but places files in /doc" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html -A mako_layout=html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dist-html: $(SPHINXBUILD) -b html -A mako_layout=html $(ALLSPHINXOPTS) .. @echo @echo "Build finished. The HTML pages are in ../." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/SQLAlchemy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/SQLAlchemy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/SQLAlchemy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/SQLAlchemy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex cp texinputs/* $(BUILDDIR)/latex/ @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) . @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." Mako-1.0.3/doc/build/namespaces.rst0000644000076500000240000003435612613724132017677 0ustar classicstaff00000000000000.. _namespaces_toplevel: ========== Namespaces ========== Namespaces are used to organize groups of defs into categories, and also to "import" defs from other files. If the file ``components.html`` defines these two defs: .. sourcecode:: mako ## components.html <%def name="comp1()"> this is comp1 <%def name="comp2(x)"> this is comp2, x is ${x} you can make another file, for example ``index.html``, that pulls those two defs into a namespace called ``comp``: .. sourcecode:: mako ## index.html <%namespace name="comp" file="components.html"/> Here's comp1: ${comp.comp1()} Here's comp2: ${comp.comp2(x=5)} The ``comp`` variable above is an instance of :class:`.Namespace`, a **proxy object** which delivers method calls to the underlying template callable using the 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 "``.``" operator. When ``import`` is used, the ``name`` attribute is optional. .. sourcecode:: mako <%namespace file="components.html" import="comp1, comp2"/> Heres comp1: ${comp1()} Heres comp2: ${comp2(x=5)} ``import`` also supports the "``*``" operator: .. sourcecode:: mako <%namespace file="components.html" import="*"/> Heres comp1: ${comp1()} Heres comp2: ${comp2(x=5)} The names imported by the ``import`` attribute take precedence over any names that exist within the current context. .. note:: In current versions of Mako, usage of ``import='*'`` is known to decrease performance of the template. This will be fixed in a future release. The ``file`` argument allows expressions -- if looking for context variables, the ``context`` must be named explicitly: .. sourcecode:: mako <%namespace name="dyn" file="${context['namespace_name']}"/> Ways to Call Namespaces ======================= There are essentially four ways to call a function from a namespace. The "expression" format, as described previously. Namespaces are just Python objects with functions on them, and can be used in expressions like any other function: .. sourcecode:: mako ${mynamespace.somefunction('some arg1', 'some arg2', arg3='some arg3', arg4='some arg4')} Synonymous with the "expression" format is the "custom tag" format, when a "closed" tag is used. This format, introduced in Mako 0.2.3, allows the usage of a "custom" Mako tag, with the function arguments passed in using named attributes: .. sourcecode:: mako <%mynamespace:somefunction arg1="some arg1" arg2="some arg2" arg3="some arg3" arg4="some arg4"/> When using tags, the values of the arguments are taken as literal strings by default. To embed Python expressions as arguments, use the embedded expression format: .. sourcecode:: mako <%mynamespace:somefunction arg1="${someobject.format()}" arg2="${somedef(5, 12)}"/> The "custom tag" format is intended mainly for namespace functions which recognize body content, which in Mako is known as a "def with embedded content": .. sourcecode:: mako <%mynamespace:somefunction arg1="some argument" args="x, y"> Some record: ${x}, ${y} The "classic" way to call defs with embedded content is the ``<%call>`` tag: .. sourcecode:: mako <%call expr="mynamespace.somefunction(arg1='some argument')" args="x, y"> Some record: ${x}, ${y} For information on how to construct defs that embed content from the caller, see :ref:`defs_with_content`. .. _namespaces_python_modules: Namespaces from Regular Python Modules ====================================== Namespaces can also import regular Python functions from modules. These callables need to take at least one argument, ``context``, an instance of :class:`.Context`. A module file ``some/module.py`` might contain the callable: .. sourcecode:: python def my_tag(context): context.write("hello world") return '' A template can use this module via: .. sourcecode:: mako <%namespace name="hw" module="some.module"/> ${hw.my_tag()} Note that the ``context`` argument is not needed in the call; the :class:`.Namespace` tag creates a locally-scoped callable which takes care of it. The ``return ''`` is so that the def does not dump a ``None`` into the output stream -- the return value of any def is rendered after the def completes, in addition to whatever was passed to :meth:`.Context.write` within its body. If your def is to be called in an "embedded content" context, that is as described in :ref:`defs_with_content`, you should use the :func:`.supports_caller` decorator, which will ensure that Mako will ensure the correct "caller" variable is available when your def is called, supporting embedded content: .. sourcecode:: python from mako.runtime import supports_caller @supports_caller def my_tag(context): context.write("
    ") context['caller'].body() context.write("
    ") return '' Capturing of output is available as well, using the outside-of-templates version of the :func:`.capture` function, which accepts the "context" as its first argument: .. sourcecode:: python from mako.runtime import supports_caller, capture @supports_caller def my_tag(context): return "
    %s
    " % \ capture(context, context['caller'].body, x="foo", y="bar") Declaring Defs in Namespaces ============================ The ``<%namespace>`` tag supports the definition of ``<%def>``\ s directly inside the tag. These defs become part of the namespace like any other function, and will override the definitions pulled in from a remote template or module: .. sourcecode:: mako ## define a namespace <%namespace name="stuff"> <%def name="comp1()"> comp1 ## then call it ${stuff.comp1()} .. _namespaces_body: The ``body()`` Method ===================== Every namespace that is generated from a template contains a method called ``body()``. This method corresponds to the main body of the template, and plays its most important roles when using inheritance relationships as well as def-calls-with-content. Since the ``body()`` method is available from a namespace just like all the other defs defined in a template, what happens if you send arguments to it? By default, the ``body()`` method accepts no positional arguments, and for usefulness in inheritance scenarios will by default dump all keyword arguments into a dictionary called ``pageargs``. But if you actually want to get at the keyword arguments, Mako recommends you define your own argument signature explicitly. You do this via using the ``<%page>`` tag: .. sourcecode:: mako <%page args="x, y, someval=8, scope='foo', **kwargs"/> A template which defines the above signature requires that the variables ``x`` and ``y`` are defined, defines default values for ``someval`` and ``scope``, and sets up ``**kwargs`` to receive all other keyword arguments. If ``**kwargs`` or similar is not present, the argument ``**pageargs`` gets tacked on by Mako. When the template is called as a top-level template (i.e. via :meth:`~.Template.render`) or via the ``<%include>`` tag, the values for these arguments will be pulled from the ``Context``. In all other cases, i.e. via calling the ``body()`` method, the arguments are taken as ordinary arguments from the method call. So above, the body might be called as: .. sourcecode:: mako ${self.body(5, y=10, someval=15, delta=7)} The :class:`.Context` object also supplies a :attr:`~.Context.kwargs` accessor, for cases when you'd like to pass along the top level context arguments to a ``body()`` callable: .. sourcecode:: mako ${next.body(**context.kwargs)} The usefulness of calls like the above become more apparent when one works with inheriting templates. For more information on this, as well as the meanings of the names ``self`` and ``next``, see :ref:`inheritance_toplevel`. .. _namespaces_builtin: Built-in Namespaces =================== The namespace is so great that Mako gives your template one (or two) for free. The names of these namespaces are ``local`` and ``self``. Other built-in namespaces include ``parent`` and ``next``, which are optional and are described in :ref:`inheritance_toplevel`. .. _namespace_local: ``local`` --------- The ``local`` namespace is basically the namespace for the currently executing template. This means that all of the top level defs defined in your template, as well as your template's ``body()`` function, are also available off of the ``local`` namespace. The ``local`` namespace is also where properties like ``uri``, ``filename``, and ``module`` and the ``get_namespace`` method can be particularly useful. .. _namespace_self: ``self`` -------- The ``self`` namespace, in the case of a template that does not use inheritance, is synonymous with ``local``. If inheritance is used, then ``self`` references the topmost template in the inheritance chain, where it is most useful for providing the ultimate form of various "method" calls which may have been overridden at various points in an inheritance chain. See :ref:`inheritance_toplevel`. Inheritable Namespaces ====================== The ``<%namespace>`` tag includes an optional attribute ``inheritable="True"``, which will cause the namespace to be attached to the ``self`` namespace. Since ``self`` is globally available throughout an inheritance chain (described in the next section), all the templates in an inheritance chain can get at the namespace imported in a super-template via ``self``. .. sourcecode:: mako ## base.html <%namespace name="foo" file="foo.html" inheritable="True"/> ${next.body()} ## somefile.html <%inherit file="base.html"/> ${self.foo.bar()} This allows a super-template to load a whole bunch of namespaces that its inheriting templates can get to, without them having to explicitly load those namespaces themselves. The ``import="*"`` part of the ``<%namespace>`` tag doesn't yet interact with the ``inheritable`` flag, so currently you have to use the explicit namespace name off of ``self``, followed by the desired function name. But more on this in a future release. Namespace API Usage Example - Static Dependencies ================================================== The ``<%namespace>`` tag at runtime produces an instance of :class:`.Namespace`. Programmatic access of :class:`.Namespace` can be used to build various kinds of scaffolding in templates and between templates. A common request is the ability for a particular template to declare "static includes" - meaning, the usage of a particular set of defs requires that certain Javascript/CSS files are present. Using :class:`.Namespace` as the object that holds together the various templates present, we can build a variety of such schemes. In particular, the :class:`.Context` has a ``namespaces`` attribute, which is a dictionary of all :class:`.Namespace` objects declared. Iterating the values of this dictionary will provide a :class:`.Namespace` object for each time the ``<%namespace>`` tag was used, anywhere within the inheritance chain. .. _namespace_attr_for_includes: Version One - Use :attr:`.Namespace.attr` ----------------------------------------- The :attr:`.Namespace.attr` attribute allows us to locate any variables declared in the ``<%! %>`` of a template. .. sourcecode:: mako ## base.mako ## base-most template, renders layout etc. ## traverse through all namespaces present, ## look for an attribute named 'includes' % for ns in context.namespaces.values(): % for incl in getattr(ns.attr, 'includes', []): ${incl} % endfor % endfor ${next.body()} ## library.mako ## library functions. <%! includes = [ '', '' ] %> <%def name="mytag()"> ${caller.body()} ## index.mako ## calling template. <%inherit file="base.mako"/> <%namespace name="foo" file="library.mako"/> <%foo:mytag> a form Above, the file ``library.mako`` declares an attribute ``includes`` inside its global ``<%! %>`` section. ``index.mako`` includes this template using the ``<%namespace>`` tag. The base template ``base.mako``, which is the inherited parent of ``index.mako`` and is reponsible for layout, then locates this attribute and iterates through its contents to produce the includes that are specific to ``library.mako``. Version Two - Use a specific named def ----------------------------------------- In this version, we put the includes into a ``<%def>`` that follows a naming convention. .. sourcecode:: mako ## base.mako ## base-most template, renders layout etc. ## traverse through all namespaces present, ## look for a %def named 'includes' % for ns in context.namespaces.values(): % if hasattr(ns, 'includes'): ${ns.includes()} % endif % endfor ${next.body()} ## library.mako ## library functions. <%def name="includes()"> <%def name="mytag()">
    ${caller.body()} ## index.mako ## calling template. <%inherit file="base.mako"/> <%namespace name="foo" file="library.mako"/> <%foo:mytag> a form In this version, ``library.mako`` declares a ``<%def>`` named ``includes``. The example works identically to the previous one, except that ``base.mako`` looks for defs named ``include`` on each namespace it examines. API Reference ============= .. autoclass:: mako.runtime.Namespace :show-inheritance: :members: .. autoclass:: mako.runtime.TemplateNamespace :show-inheritance: :members: .. autoclass:: mako.runtime.ModuleNamespace :show-inheritance: :members: .. autofunction:: mako.runtime.supports_caller .. autofunction:: mako.runtime.capture Mako-1.0.3/doc/build/requirements.txt0000644000076500000240000000005212613724132020274 0ustar classicstaff00000000000000changelog>=0.3.4 sphinx-paramlinks>=0.2.0 Mako-1.0.3/doc/build/runtime.rst0000644000076500000240000003741112613724132017236 0ustar classicstaff00000000000000.. _runtime_toplevel: ============================ The Mako Runtime Environment ============================ This section describes a little bit about the objects and built-in functions that are available in templates. .. _context: Context ======= The :class:`.Context` is the central object that is created when a template is first executed, and is responsible for handling all communication with the outside world. Within the template environment, it is available via the :ref:`reserved name ` ``context``. The :class:`.Context` includes two major components, one of which is the output buffer, which is a file-like object such as Python's ``StringIO`` or similar, and the other a dictionary of variables that can be freely referenced within a template; this dictionary is a combination of the arguments sent to the :meth:`~.Template.render` function and some built-in variables provided by Mako's runtime environment. The Buffer ---------- The buffer is stored within the :class:`.Context`, and writing to it is achieved by calling the :meth:`~.Context.write` method -- in a template this looks like ``context.write('some string')``. You usually don't need to care about this, as all text within a template, as well as all expressions provided by ``${}``, automatically send everything to this method. The cases you might want to be aware of its existence are if you are dealing with various filtering/buffering scenarios, which are described in :ref:`filtering_toplevel`, or if you want to programmatically send content to the output stream, such as within a ``<% %>`` block. .. sourcecode:: mako <% context.write("some programmatic text") %> The actual buffer may or may not be the original buffer sent to the :class:`.Context` object, as various filtering/caching scenarios may "push" a new buffer onto the context's underlying buffer stack. For this reason, just stick with ``context.write()`` and content will always go to the topmost buffer. .. _context_vars: Context Variables ----------------- When your template is compiled into a Python module, the body content is enclosed within a Python function called ``render_body``. Other top-level defs defined in the template are defined within their own function bodies which are named after the def's name with the prefix ``render_`` (i.e. ``render_mydef``). One of the first things that happens within these functions is that all variable names that are referenced within the function which are not defined in some other way (i.e. such as via assignment, module level imports, etc.) are pulled from the :class:`.Context` object's dictionary of variables. This is how you're able to freely reference variable names in a template which automatically correspond to what was passed into the current :class:`.Context`. * **What happens if I reference a variable name that is not in 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 :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. * **UNDEFINED makes it hard for me to find what name is missing** - An alternative is to specify the option ``strict_undefined=True`` to the :class:`.Template` or :class:`.TemplateLookup`. This will cause any non-present variables to raise an immediate ``NameError`` which includes the name of the variable in its message when :meth:`~.Template.render` is called -- ``UNDEFINED`` is not used. .. versionadded:: 0.3.6 * **Why not just return None?** Using ``UNDEFINED``, or raising a ``NameError`` is more explicit and allows differentiation between a value of ``None`` that was explicitly passed to the :class:`.Context` and a value that wasn't present at all. * **Why raise an exception when you call str() on it ? Why not just return a blank string?** - Mako tries to stick to the Python philosophy of "explicit is better than implicit". In this case, it's decided that the template author should be made to specifically handle a missing value rather than experiencing what may be a silent failure. Since ``UNDEFINED`` is a singleton object just like Python's ``True`` or ``False``, you can use the ``is`` operator to check for it: .. sourcecode:: mako % if someval is UNDEFINED: someval is: no value % else: someval is: ${someval} % endif Another facet of the :class:`.Context` is that its dictionary of variables is **immutable**. Whatever is set when :meth:`~.Template.render` is called is what stays. Of course, since its Python, you can hack around this and change values in the context's internal dictionary, but this will probably will not work as well as you'd think. The reason for this is that Mako in many cases creates copies of the :class:`.Context` object, which get sent to various elements of the template and inheriting templates used in an execution. So changing the value in your local :class:`.Context` will not necessarily make that value available in other parts of the template's execution. Examples of where Mako creates copies of the :class:`.Context` include within top-level def calls from the main body of the template (the context is used to propagate locally assigned variables into the scope of defs; since in the template's body they appear as inlined functions, Mako tries to make them act that way), and within an inheritance chain (each template in an inheritance chain has a different notion of ``parent`` and ``next``, which are all stored in unique :class:`.Context` instances). * **So what if I want to set values that are global to everyone within a template request?** - All you have to do is provide a dictionary to your :class:`.Context` when the template first runs, and everyone can just get/set variables from that. Lets say its called ``attributes``. Running the template looks like: .. sourcecode:: python output = template.render(attributes={}) Within a template, just reference the dictionary: .. sourcecode:: mako <% attributes['foo'] = 'bar' %> 'foo' attribute is: ${attributes['foo']} * **Why can't "attributes" be a built-in feature of the Context?** - This is an area where Mako is trying to make as few decisions about your application as it possibly can. Perhaps you don't want your templates to use this technique of assigning and sharing data, or perhaps you have a different notion of the names and kinds of data structures that should be passed around. Once again Mako would rather ask the user to be explicit. Context Methods and Accessors ----------------------------- Significant members of :class:`.Context` include: * ``context[key]`` / ``context.get(key, default=None)`` - dictionary-like accessors for the context. Normally, any variable you use in your template is automatically pulled from 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 present, like a dictionary it raises ``KeyError``. * ``keys()`` - all the names defined within this context. * ``kwargs`` - this returns a **copy** of the context's dictionary of variables. This is useful when you want to propagate the variables in the current context to a function as keyword arguments, i.e.: .. sourcecode:: mako ${next.body(**context.kwargs)} * ``write(text)`` - write some text to the current output stream. * ``lookup`` - returns the :class:`.TemplateLookup` instance that is used for all file-lookups within the current execution (even though individual :class:`.Template` instances can conceivably have different instances of a :class:`.TemplateLookup`, only the :class:`.TemplateLookup` of the originally-called :class:`.Template` gets used in a particular execution). .. _loop_context: The Loop Context ================ Within ``% for`` blocks, the :ref:`reserved name` ``loop`` is available. ``loop`` tracks the progress of the ``for`` loop and makes it easy to use the iteration state to control template behavior: .. sourcecode:: mako
      % for a in ("one", "two", "three"):
    • Item ${loop.index}: ${a}
    • % endfor
    .. versionadded:: 0.7 Iterations ---------- Regardless of the type of iterable you're looping over, ``loop`` always tracks the 0-indexed iteration count (available at ``loop.index``), its parity (through the ``loop.even`` and ``loop.odd`` bools), and ``loop.first``, a bool indicating whether the loop is on its first iteration. If your iterable provides a ``__len__`` method, ``loop`` also provides access to a count of iterations remaining at ``loop.reverse_index`` and ``loop.last``, a bool indicating whether the loop is on its last iteration; accessing these without ``__len__`` will raise a ``TypeError``. Cycling ------- Cycling is available regardless of whether the iterable you're using provides a ``__len__`` method. Prior to Mako 0.7, you might have generated a simple zebra striped list using ``enumerate``: .. sourcecode:: mako
      % for i, item in enumerate(('spam', 'ham', 'eggs')):
    • ${item}
    • % endfor
    With ``loop.cycle``, you get the same results with cleaner code and less prep work: .. sourcecode:: mako
      % for item in ('spam', 'ham', 'eggs'):
    • ${item}
    • % endfor
    Both approaches produce output like the following: .. sourcecode:: html
    • spam
    • ham
    • eggs
    Parent Loops ------------ Loop contexts can also be transparently nested, and the Mako runtime will do the right thing and manage the scope for you. You can access the parent loop context through ``loop.parent``. This allows you to reach all the way back up through the loop stack by chaining ``parent`` attribute accesses, i.e. ``loop.parent.parent....`` as long as the stack depth isn't exceeded. For example, you can use the parent loop to make a checkered table: .. sourcecode:: mako
% for consonant in 'pbj': % for vowel in 'iou': % endfor % endfor
${consonant + vowel}t
.. sourcecode:: html
pit pot put
bit bot but
jit jot jut
.. _migrating_loop: Migrating Legacy Templates that Use the Word "loop" --------------------------------------------------- .. versionchanged:: 0.7 The ``loop`` name is now :ref:`reserved ` in Mako, which means a template that refers to a variable named ``loop`` won't function correctly when used in Mako 0.7. To ease the transition for such systems, the feature can be disabled across the board for all templates, then re-enabled on a per-template basis for those templates which wish 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: .. sourcecode:: python lookup = TemplateLookup(directories=['/docs'], enable_loop=False) or: .. sourcecode:: python template = Template("some template", enable_loop=False) An individual template can make usage of the feature when ``enable_loop`` is set to ``False`` by switching it back on within the ``<%page>`` tag: .. sourcecode:: mako <%page enable_loop="True"/> % for i in collection: ${i} ${loop.index} % endfor Using the above scheme, it's safe to pass the name ``loop`` to the :meth:`.Template.render` method as well as to freely make usage of a variable named ``loop`` within a template, provided the ``<%page>`` tag doesn't override it. New templates that want to use the ``loop`` context can then set up ``<%page enable_loop="True"/>`` to use the new feature without affecting old templates. All the Built-in Names ====================== A one-stop shop for all the names Mako defines. Most of these names are instances of :class:`.Namespace`, which are described in the next section, :ref:`namespaces_toplevel`. Also, most of these names other than ``context``, ``UNDEFINED``, and ``loop`` are also present *within* the :class:`.Context` itself. The names ``context``, ``loop`` and ``UNDEFINED`` themselves can't be passed to the context and can't be substituted -- see the section :ref:`reserved_names`. * ``context`` - this is the :class:`.Context` object, introduced at :ref:`context`. * ``local`` - the namespace of the current template, described in :ref:`namespaces_builtin`. * ``self`` - the namespace of the topmost template in an inheritance chain (if any, otherwise the same as ``local``), mostly described in :ref:`inheritance_toplevel`. * ``parent`` - the namespace of the parent template in an inheritance chain (otherwise undefined); see :ref:`inheritance_toplevel`. * ``next`` - the namespace of the next template in an inheritance chain (otherwise undefined); see :ref:`inheritance_toplevel`. * ``caller`` - a "mini" namespace created when using the ``<%call>`` tag to define a "def call with content"; described in :ref:`defs_with_content`. * ``loop`` - this provides access to :class:`.LoopContext` objects when they are requested within ``% for`` loops, introduced at :ref:`loop_context`. * ``capture`` - a function that calls a given def and captures its resulting content into a string, which is returned. Usage is described in :ref:`filtering_toplevel`. * ``UNDEFINED`` - a global singleton that is applied to all otherwise uninitialized template variables that were not located within the :class:`.Context` when rendering began, unless the :class:`.Template` flag ``strict_undefined`` is set to ``True``. ``UNDEFINED`` is 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 ``<%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 makes no sense, it shouldn't; read the section :ref:`namespaces_body`. .. _reserved_names: Reserved Names -------------- Mako has a few names that are considered to be "reserved" and can't be used as variable names. .. versionchanged:: 0.7 Mako raises an error if these words are found passed to the template as context arguments, whereas in previous versions they'd be silently ignored or lead to other error messages. * ``context`` - see :ref:`context`. * ``UNDEFINED`` - see :ref:`context_vars`. * ``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 ============= .. autoclass:: mako.runtime.Context :show-inheritance: :members: .. autoclass:: mako.runtime.LoopContext :show-inheritance: :members: .. autoclass:: mako.runtime.Undefined :show-inheritance: Mako-1.0.3/doc/build/static/0000755000076500000240000000000012613724373016311 5ustar classicstaff00000000000000Mako-1.0.3/doc/build/static/docs.css0000644000076500000240000001554212613724132017753 0ustar classicstaff00000000000000/* global */ body { background-color: #FDFBFC; margin:38px; color:#333333; } a { font-weight:normal; text-decoration:none; } form { display:inline; } /* hyperlinks */ a:link, a:visited, a:active { color:#0000FF; } a:hover { color:#700000; text-decoration:underline; } /* paragraph links after sections. These aren't visible until hovering over the tag, then have a "reverse video" effect over the actual link */ a.headerlink { font-size: 0.8em; padding: 0 4px 0 4px; text-decoration: none; visibility: hidden; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink { visibility: visible; } a.headerlink:hover { background-color: #990000; color: white; } /* Container setup */ #docs-container { max-width:1000px; } /* header/footer elements */ #docs-header h1 { font-size:20px; color: #222222; margin: 0; padding: 0; } #docs-header { font-family:Tahoma, Geneva,sans-serif; font-size:.9em; } #docs-top-navigation, #docs-bottom-navigation { font-family: Tahoma, Geneva, sans-serif; background-color: #EEE; border: solid 1px #CCC; padding:10px; font-size:.9em; } #docs-top-navigation { margin:10px 0px 10px 0px; line-height:1.2em; } .docs-navigation-links { font-family:Tahoma, Geneva,sans-serif; } #docs-bottom-navigation { float:right; margin: 1em 0 1em 5px; } #docs-copyright { font-size:.85em; padding:5px 0px; } #docs-header h1, #docs-top-navigation h1, #docs-top-navigation h2 { font-family:Tahoma,Geneva,sans-serif; font-weight:normal; } #docs-top-navigation h2 { margin:16px 4px 7px 5px; font-size:2em; } #docs-search { float:right; } #docs-top-page-control { float:right; width:350px; } #docs-top-page-control ul { padding:0; margin:0; } #docs-top-page-control li { list-style-type:none; padding:1px 8px; } #docs-container .version-num { font-weight: bold; } /* content container, sidebar */ #docs-body-container { background-color:#EFEFEF; border: solid 1px #CCC; } #docs-body, #docs-sidebar { /*font-family: helvetica, arial, sans-serif; font-size:.9em;*/ font-family: Tahoma, Geneva, sans-serif; /*font-size:.85em;*/ line-height:1.5em; } #docs-sidebar > ul { font-size:.9em; } #docs-sidebar { float:left; width:212px; padding: 10px 0 0 15px; /*font-size:.85em;*/ } #docs-sidebar h3, #docs-sidebar h4 { background-color: #DDDDDD; color: #222222; font-family: Tahoma, Geneva,sans-serif; font-size: 1.1em; font-weight: normal; margin: 10px 0 0 -15px; padding: 5px 10px 5px 10px; text-shadow: 1px 1px 0 white; width:210px; } #docs-sidebar h3 a, #docs-sidebar h4 a { color: #222222; } #docs-sidebar ul { margin: 10px 10px 10px 0px; padding: 0; list-style: none outside none; } #docs-sidebar ul ul { margin-bottom: 0; margin-top: 0; list-style: square outside none; margin-left: 20px; } #docs-body { background-color:#FFFFFF; padding:1px 10px 10px 10px; } #docs-body.withsidebar { margin: 0 0 0 230px; border-left:3px solid #DFDFDF; } #docs-body h1, #docs-body h2, #docs-body h3, #docs-body h4 { font-family:Tahoma, Geneva, sans-serif; } #docs-body h1 { /* hide the

for each content section. */ display:none; font-size:1.8em; } #docs-body h2 { font-size:1.6em; } #docs-body h3 { font-size:1.4em; } /* SQL popup, code styles */ .highlight { background:none; } #docs-container pre { font-size:1.2em; } #docs-container .pre { font-size:1.1em; } #docs-container pre { background-color: #f0f0f0; border: solid 1px #ccc; box-shadow: 2px 2px 3px #DFDFDF; padding:10px; margin: 5px 0px 5px 0px; overflow:auto; line-height:1.3em; } .popup_sql, .show_sql { background-color: #FBFBEE; padding:5px 10px; margin:10px -5px; border:1px dashed; } /* the [SQL] links used to display SQL */ #docs-container .sql_link { font-weight:normal; font-family: arial, sans-serif; font-size:.9em; text-transform: uppercase; color:#990000; border:1px solid; padding:1px 2px 1px 2px; margin:0px 10px 0px 15px; float:right; line-height:1.2em; } #docs-container a.sql_link, #docs-container .sql_link { text-decoration: none; padding:1px 2px; } #docs-container a.sql_link:hover { text-decoration: none; color:#fff; border:1px solid #900; background-color: #900; } /* docutils-specific elements */ th.field-name { text-align:right; } div.note, div.warning, p.deprecated, div.topic { background-color:#EEFFEF; } div.admonition, div.topic, p.deprecated, p.versionadded, p.versionchanged { border:1px solid #CCCCCC; padding:5px 10px; font-size:.9em; box-shadow: 2px 2px 3px #DFDFDF; } div.warning .admonition-title { color:#FF0000; } div.admonition .admonition-title, div.topic .topic-title { font-weight:bold; } .viewcode-back, .viewcode-link { float:right; } dl.function > dt, dl.attribute > dt, dl.classmethod > dt, dl.method > dt, dl.class > dt, dl.exception > dt { background-color:#F0F0F0; margin:25px -10px 10px 10px; padding: 0px 10px; } p.versionadded span.versionmodified, p.versionchanged span.versionmodified, p.deprecated span.versionmodified { background-color: #F0F0F0; font-style: italic; } dt:target, span.highlight { background-color:#FBE54E; } a.headerlink { font-size: 0.8em; padding: 0 4px 0 4px; text-decoration: none; visibility: hidden; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink { visibility: visible; } a.headerlink:hover { background-color: #00f; color: white; } .clearboth { clear:both; } tt.descname { background-color:transparent; font-size:1.2em; font-weight:bold; } tt.descclassname { background-color:transparent; } tt { background-color:#ECF0F3; padding:0 1px; } /* syntax highlighting overrides */ .k, .kn {color:#0908CE;} .o {color:#BF0005;} .go {color:#804049;} /* special "index page" sections with specific formatting */ div#sqlalchemy-documentation { font-size:.95em; } div#sqlalchemy-documentation em { font-style:normal; } div#sqlalchemy-documentation .rubric{ font-size:14px; background-color:#EEFFEF; padding:5px; border:1px solid #BFBFBF; } div#sqlalchemy-documentation a, div#sqlalchemy-documentation li { padding:5px 0px; } div#getting-started { border-bottom:1px solid; } div#sqlalchemy-documentation div#sqlalchemy-orm { float:left; width:48%; } div#sqlalchemy-documentation div#sqlalchemy-core { float:left; width:48%; margin:0; padding-left:10px; border-left:1px solid; } div#dialect-documentation { border-top:1px solid; /*clear:left;*/ } Mako-1.0.3/doc/build/static/makoLogo.png0000644000076500000240000002670312613724132020570 0ustar classicstaff00000000000000PNG  IHDRd gAMAOX2tEXtSoftwareAdobe ImageReadyqe<-UIDATxb?(D`cgprrb022b#'O0̚5a >| V+&<K s1k@ 4? Y 7k@f0@1fQ0Й ]!-Qzoܸð~zwR. @l Ħ@F e{@|7hbeQ<,-->}.xBBX-9@_Ak$Z4Zϟ3,_ٳg)BXw MϠr e bHKKcb/fϟ?&@ 4hT?~d>}:r')A};@;8/" 5#mxS fB4Z'O2XXX C3\$t vWx?o#q;ڟ\\\~~~!!!AAA{2 L6 9!@D6 >G W# !! ++ˠȠag,P:;;TBGh3i BCk $6qt(Ԡ --k='466 M@̂YFM͛7#k֬a.elV J${4ɀ<A527o0|ŋ`a`u eeeb >lFRR@4pB`-/&{[}/H:u?0wʔ)l"6(\3[X QK???phBt~ ֭[ 0x4؟"I/(b\5pyy94F1'e6& ΝL?`ݰ_b8^ZZ\  F#}hf7ukd0L\8ʖd`3ß4٣xm0@o@3O>2 E_> .0p F#y jzch2Y[[7ݽ&>`( zt$ N(7ߴi:Z {PTTDp@xPv35ا?Ro4x}Wj_ɮ.Sj FW|݃ @(j sfq;w*++SPbahPn?[]]}zg?S@o߾Qpd :t2f̘,Z{O SVBjd 01ւw7#z }z@gA; ht 8wۑ@˂ЦJW ʰd%%%Z@530|F=!ttY5Ȥ~Xg w7fY#(ymhc&hSEE'xsQ H=H`gf.Y MhDQUU0!Ј"B):舂*T[ԩS qZm.~ *7 DQ }`f1Ҩw t` YdáG޽]ȍAٱcM->f_UgL _fh:7@2|pe4 F3fZ&}kTO"&At4qÁ$U&ph. hy_z~ \zzUd۷if@dC"hQ&C*rȜG"dC>d4d 6˒% :1d7Zd.Ҭ&e]< 4<VP 0Lh&03031iZf>:PKpV9Y'}h\de2*ˌ(,fa /Qd'M4>gÛ_ @#t @fp2 3d_>}V`Ăfgcjݟn7d(APAi >NvN6A>. 4k.OiZ.eU p߹u$3 XN]yHNO _dLp EL 4PXZ/0Q~ex Ãgo%6zD L$? r beo> -@ aZB'8ؘy!NdhQ@髏 7LF6Y63prr1X._m:BMqqe^ՠD%0y˷_R$$6bFA /~f0ӑǨm|ps_0mHؙ '#;} *M_ppgfgtMx3!Aih,űg6@&-2r ^'M4K0@qMt,=]{D+@5(X K3 搀bO@_ ̐B oXSIAVB#dTdcB'T7#0"2iu*M2 !FAW! (aR2WXY3(%.aF)0ȃ ǖv>@| t# 9kw2{<8+Qj’^@  ī[@ yŅx$Dp7A?|$?2h%hf Z4o.Bl';;lDN ƃ)y !iz_LťIVa%=Cua:x @19y'zAC_w 5# 0e1@.z$LЅRt7t1(#g3@.Z#5t@5\`&֯<4pq`+qBd% Y N٨C3B`M~fb0Rt<~f8~>A5M!j"'haRC32|l3Æ (]gj,N޼vٟrndfX ;;C ï_XΣW1g ّ& XֆQc 5(YTӜvQ!3$PM Tӂ.jxHS߳ep߈UtC O!JDžzt+!/3V} ͠ - m.B2 BOז% [*{ XB{~|?s CazYh*Gpqk^>~)9n0~!a _]jbK! X K P@K5wP3QOL%{@jo޽g8}0A'Ⱞ0ˀ 2h j%>ge7yAqʙ d֏XX+DcA`xj8{2[ l- )\`w gEeUL&#>yY K\H9~ф@L7^Rt6^&v ^4$ @`*#Ġ@m?`ÕOão#3uȟӁX6{P`A>`nS?ُn `n: /_>1ϟ?ɠcZebPQPVÐWTVc1`ǰ%g2bu-0 A2Өu:@~A}5}1AAИ7^^ fS00qa@k_{Po gއ4S&cd0#ͥq> ϟ?AM9ATkakhА:1t@e.x@ t'0@P"ڂ@A`4,=$p :4PŁ`@[D8 fϧO@exEuqIiϟRBL\^Z)''Q& +7f j T ObAT h[h@2)`SJ[;0|@dLi?|A:lƁ4pb MOĀ $2Ȍx̭6]@\pM/G"x-3@lWf`ce5DIM6t=CV 27BD>(ـvQT`8ނq@)l 4 &OkWVP [dz < ߾b=junf3W0r1% @CY Tg@:& f41@&׉]{C{'…h$hNOJX|X8ϤEys(4 <\]F{H3?8S2&6íW(k nFA52? ǐ5fV2A @wK)ZP@ | 7 ԤOLJDHUy:.Gbd` L#`;B6Yj@V@JQLF8W ͬ[U~/`T;VÐ݇LjB2-<W^~jPf@"~dx ݇T? F_ -O*{Hh.ȴCw&3&_0/F-3(ĠQKo l@躧T kfl&{ O1> ]@߿#pv ex5ٶ@}?>` jzB2 skK dX[d D́P{_  6rf'/ -Aͼ*x3311lw: g@'mN`iTZg-~)H/;c-fyTm{ @ىQMdQ` L;0Q` A{/qtfX|}_ ?d/..Hiix&XEAG^0*JFMZVL<@U`mW- @ *Z`*Mp{k&y T&~vxT̈́F%}JҀG121"4C1zُht '&w9h$N%~Jk t~6߸@+Giwdؾy-6"Ho^}UU (AWC[;HT>Z E߭dDS`8212Ʊ 5)K)9% `S #)׏)hrߊN?b޼m#\tύ>xYH-#pjg|l @fd:Dž(;m#~دT `DZegpfVGL2`ϤŸ}Bv?K VvN`x~>@ |8`i~h؁.~ 4#UK̍La;d.T'P\@J03!f,^(H/ CkЦUȾ)pՖ߾~aE 0Phې4l3&3A-l菞~EPD 06/ANvmvܩ/=m#"" +w;Vw;?d/E rbvr1\qPyoA Q3p O~-C ]4!o}Ȱc1ZzܡtM0A XG?UP4v6t l:  f hf+Q2J082lZ,M֊:F2*7L);}-k!|VFFVp5 ltx8^}p%0Ph 4 ,!!@囷;T0 ްm?A}aL@@ zee ڏjuh%}( Ip!: b"Bt=SL͛] ߽!]wolhjqˉ>mXz&G >@#q!SPoP@;(Z\' LPYE0s5Дn!i -aΚM;=@w`T;O  A]Me`/~); ~P] yAP^IL@ɐ;0E:z,rgh ^KUAC N 4``g2P.ZtSCؠL ̬ ~! Hmu}Q/yɽk "7i'U.Of.8TQf#mV&d~9c f O=32B}V8y- j?UܽumZW@h- v1Mÿ ?/m_UT2-4@C0V%Ʒށ'ݑ<#;zML1.,6+P_4ZXX:{ v\d`6 (RiC퓁Ũhf&zFr7F匠>##$/-U& TSMa 4P3C 8%?3kۺqU9tw!oX )d2nMVdԍE:r VQͤ0ش Y/T[ fl! !NoFNׯ B"J*-7^@99`n +(?Ӭz WD>] TV̳PquR%XLLLqșˁr< -LnZ30)M?ghP&-M<򗃓EXTL4XAf:e7Y@Q&\aMbtdhNghQPBlfàx_ȹ\o߾C c0|=z"o_89A,ǏVj:7o]يa , (o^ A? G S. d[*Ԕmxy!+>pi;,It6^C=-  *|0"&ɨ7 '`|$1O~89\ -A gAf=X*@! *Z ۿm=Lr@_8)0t 覞+33nt ?# D Wx *.":iG,]]X4sZR0 0_pاeFu4'@fӷojMa^=_,\N?2x3()Pl(@Ѥz9'aB ZY;7̔;q 0 J1'ƠytЀ(ۘ08P`rs/ w'6ivj_qml@4@QH( : 0'@B[ t)0.6,11AR%EBf8@QwMM 5%10efu#OB< ^*d2I^=kg6|f4`XSUCNvfbb R`gO0\|/ g(--ePQQ>8!k?I `JaA64 N@N09s(ЦI%`ash>:͝m/>G'0ӡM T8;gWt3|'޿{/=ax 5k!|dVu3##J͆\QX~ΓG* op-B^PH24o0@RԒ@ÁAj$LLYYپ}aӚe~@GT.K9mX@\}HPMSưUyæm;޽՘Q RJPL3Z_ P!'=wЇ7`S6;$%j =}^2c{(JT-iM@ Ԅla;w=@,si apa0aرk?ñ^~ p%U{#*3"@A,%-CMw2 -]E8`4c8|$ÁCG3`" zb%"hj!ڏ+ZOO!++ARRxEȐpWK4ob8u<{޽N;PjBFb J f&Z i&5MY3]pm`5ް7;({Ν::;Ա $Ѡ튊A] vAAқG:Ǐ^y /hTNB\ Q2(~X{̙ K,^CA`+*l_D78>SQ&((ƣ`p5;+3xI th1&Z`1 F3(v@R & @fQ0.\ TkR@ CNV`PW'm F3(v:XAH" 2 P[HJ3htc ;;UUU0 jt (%4bP)hbYY fj 37'3Cee%M2h&a~sYˋnL6 %S4u @fQ0,FKPMfAMD%%% F3(@FFA_eK >Y& -4FgLIwrss%L6 - hedP4F jj(4_b'L6 -F9? + F3(tZq74>i%0“"XIENDB`Mako-1.0.3/doc/build/static/site.css0000644000076500000240000000221712613724132017762 0ustar classicstaff00000000000000body { font-family: Tahoma, Geneva, sans-serif; line-height:1.4em; margin:15px; background-color:#FFFFFF; } img {border:none;} a { text-decoration: none;} a:visited { color: #2929ff;} a:hover { color: #0000ff;} #wrap { margin:0 auto; max-width:1024px; min-width:480px; position:relative; } h1 { font-size:1.6em; font-weight:bold; } h2 { font-size:1.1em; font-weight:bold; margin:10px 0px 10px 0px; } .clearfix{ clear:both; } .red { font-weight:bold; color:#FF0000; } .rightbar { float:right; } .slogan { margin-top:10px; } #gittip_nav { float:right; margin:10px 0px 0px 0px; } .toolbar { margin-top:20px; } .copyright { font-size:.8em; text-align:center; color:909090; } .pylogo { text-align:right; float:right; } .code { font-family:monospace; } li { margin:1px 0px 1px 0px; } .speedchart td { font-size:small; } pre.codesample { margin: 1.5em; padding: .5em; font-size: .95em; line-height:1em; background-color: #eee; border: 1px solid #ccc; width:450px; overflow:auto; } #speedchart { margin:5px 10px 5px 10px; } Mako-1.0.3/doc/build/syntax.rst0000644000076500000240000003273112613724132017101 0ustar classicstaff00000000000000.. _syntax_toplevel: ====== Syntax ====== A Mako template is parsed from a text stream containing any kind of content, XML, HTML, email text, etc. The template can further contain Mako-specific directives which represent variable and/or expression substitutions, control structures (i.e. conditionals and loops), server-side comments, full blocks of Python code, as well as various tags that offer additional functionality. All of these constructs compile into real Python code. This means that you can leverage the full power of Python in almost every aspect of a Mako template. Expression Substitution ======================= The simplest expression is just a variable substitution. The syntax for this is the ``${}`` construct, which is inspired by Perl, Genshi, JSP EL, and others: .. sourcecode:: mako this is x: ${x} Above, the string representation of ``x`` is applied to the template's output stream. If you're wondering where ``x`` comes from, 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. The contents within the ``${}`` tag are evaluated by Python directly, so full expressions are OK: .. sourcecode:: mako pythagorean theorem: ${pow(x,2) + pow(y,2)} The results of the expression are evaluated into a string result in all cases before being rendered to the output stream, such as the above example where the expression produces a numeric result. Expression Escaping =================== Mako includes a number of built-in escaping mechanisms, including HTML, URI and XML escaping, as well as a "trim" function. These escapes can be added to an expression substitution using the ``|`` operator: .. sourcecode:: mako ${"this is some text" | u} The above expression applies URL escaping to the expression, and produces ``this+is+some+text``. The ``u`` name indicates URL escaping, whereas ``h`` represents HTML escaping, ``x`` represents XML escaping, and ``trim`` applies a trim function. Read more about built-in filtering functions, including how to make your own filter functions, in :ref:`filtering_toplevel`. Control Structures ================== A control structure refers to all those things that control the flow of a program -- conditionals (i.e. ``if``/``else``), loops (like ``while`` and ``for``), as well as things like ``try``/``except``. In Mako, control structures are written using the ``%`` marker followed by a regular Python control expression, and are "closed" by using another ``%`` marker with the tag "``end``", where "````" is the keyword of the expression: .. sourcecode:: mako % if x==5: this is some output % endif The ``%`` can appear anywhere on the line as long as no text precedes it; indentation is not significant. The full range of Python "colon" expressions are allowed here, including ``if``/``elif``/``else``, ``while``, ``for``, and even ``def``, although Mako has a built-in tag for defs which is more full-featured. .. sourcecode:: mako % for a in ['one', 'two', 'three', 'four', 'five']: % if a[0] == 't': its two or three % elif a[0] == 'f': four/five % else: one % endif % endfor The ``%`` sign can also be "escaped", if you actually want to emit a percent sign as the first non whitespace character on a line, by escaping it as in ``%%``: .. sourcecode:: mako %% some text %% some more text The Loop Context ---------------- The **loop context** provides additional information about a loop while inside of a ``% for`` structure: .. sourcecode:: mako
    % for a in ("one", "two", "three"):
  • Item ${loop.index}: ${a}
  • % endfor
See :ref:`loop_context` for more information on this feature. .. versionadded:: 0.7 Comments ======== Comments come in two varieties. The single line comment uses ``##`` as the first non-space characters on a line: .. sourcecode:: mako ## this is a comment. ...text ... A multiline version exists using ``<%doc> ...text... ``: .. sourcecode:: mako <%doc> these are comments more comments Newline Filters =============== The backslash ("``\``") character, placed at the end of any line, will consume the newline character before continuing to the next line: .. sourcecode:: mako here is a line that goes onto \ another line. The above text evaluates to: .. sourcecode:: text here is a line that goes onto another line. Python Blocks ============= Any arbitrary block of python can be dropped in using the ``<% %>`` tags: .. sourcecode:: mako this is a template <% x = db.get_resource('foo') y = [z.element for z in x if x.frobnizzle==5] %> % for elem in y: element: ${elem} % endfor Within ``<% %>``, you're writing a regular block of Python code. While the code can appear with an arbitrary level of preceding whitespace, it has to be consistently formatted with itself. Mako's compiler will adjust the block of Python to be consistent with the surrounding generated Python code. Module-level Blocks =================== A variant on ``<% %>`` is the module-level code block, denoted by ``<%! %>``. Code within these tags is executed at the module level of the template, and not within the rendering function of the template. Therefore, this code does not have access to the template's context and is only executed when the template is loaded into memory (which can be only once per application, or more, depending on the runtime environment). Use the ``<%! %>`` tags to declare your template's imports, as well as any pure-Python functions you might want to declare: .. sourcecode:: mako <%! import mylib import re def filter(text): return re.sub(r'^@', '', text) %> Any number of ``<%! %>`` blocks can be declared anywhere in a template; they will be rendered in the resulting module in a single contiguous block above all render callables, in the order in which they appear in the source template. Tags ==== The rest of what Mako offers takes place in the form of tags. All tags use the same syntax, which is similar to an XML tag except that the first character of the tag name is a ``%`` character. The tag is closed either by a contained slash character, or an explicit closing tag: .. sourcecode:: mako <%include file="foo.txt"/> <%def name="foo" buffered="True"> this is a def All tags have a set of attributes which are defined for each tag. Some of these attributes are required. Also, many attributes support **evaluation**, meaning you can embed an expression (using ``${}``) inside the attribute text: .. sourcecode:: mako <%include file="/foo/bar/${myfile}.txt"/> Whether or not an attribute accepts runtime evaluation depends on the type of tag and how that tag is compiled into the template. The best way to find out if you can stick an expression in is to try it! The lexer will tell you if it's not valid. Heres a quick summary of all the tags: ``<%page>`` ----------- This tag defines general characteristics of the template, including caching arguments, and optional lists of arguments which the template expects when invoked. .. sourcecode:: mako <%page args="x, y, z='default'"/> Or a page tag that defines caching characteristics: .. sourcecode:: mako <%page cached="True" cache_type="memory"/> Currently, only one ``<%page>`` tag gets used per template, the rest get ignored. While this will be improved in a future release, for now make sure you have only one ``<%page>`` tag defined in your template, else you may not get the results you want. The details of what ``<%page>`` is used for are described further in :ref:`namespaces_body` as well as :ref:`caching_toplevel`. ``<%include>`` -------------- A tag that is familiar from other template languages, ``%include`` is a regular joe that just accepts a file argument and calls in the rendered result of that file: .. sourcecode:: mako <%include file="header.html"/> hello world <%include file="footer.html"/> Include also accepts arguments which are available as ``<%page>`` arguments in the receiving template: .. sourcecode:: mako <%include file="toolbar.html" args="current_section='members', username='ed'"/> ``<%def>`` ---------- The ``%def`` tag defines a Python function which contains a set of content, that can be called at some other point in the template. The basic idea is simple: .. sourcecode:: mako <%def name="myfunc(x)"> this is myfunc, x is ${x} ${myfunc(7)} The ``%def`` tag is a lot more powerful than a plain Python ``def``, as the Mako compiler provides many extra services with ``%def`` that you wouldn't normally have, such as the ability to export defs as template "methods", automatic propagation of the current :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`. ``<%block>`` ------------ ``%block`` is a tag that is close to a ``%def``, except executes itself immediately in its base-most scope, and can also be anonymous (i.e. with no name): .. sourcecode:: mako <%block filter="h"> some stuff. Inspired by Jinja2 blocks, named blocks offer a syntactically pleasing way to do inheritance: .. sourcecode:: mako <%block name="header">

<%block name="title"/>

${self.body()} Blocks are introduced in :ref:`blocks` and further described in :ref:`inheritance_toplevel`. .. versionadded:: 0.4.1 ``<%namespace>`` ---------------- ``%namespace`` is Mako's equivalent of Python's ``import`` statement. It allows access to all the rendering functions and metadata of other template files, plain Python modules, as well as locally defined "packages" of functions. .. sourcecode:: mako <%namespace file="functions.html" import="*"/> The underlying object generated by ``%namespace``, an instance of :class:`.mako.runtime.Namespace`, is a central construct used in templates to reference template-specific information such as the current URI, inheritance structures, and other things that are not as hard as they sound right here. Namespaces are described in :ref:`namespaces_toplevel`. ``<%inherit>`` -------------- Inherit allows templates to arrange themselves in **inheritance chains**. This is a concept familiar in many other template languages. .. sourcecode:: mako <%inherit file="base.html"/> When using the ``%inherit`` tag, control is passed to the topmost inherited template first, which then decides how to handle calling areas of content from its inheriting templates. Mako offers a lot of flexibility in this area, including dynamic inheritance, content wrapping, and polymorphic method calls. Check it out in :ref:`inheritance_toplevel`. ``<%``\ nsname\ ``:``\ defname\ ``>`` ------------------------------------- Any user-defined "tag" can be created against a namespace by using a tag with a name of the form ``<%:>``. The closed and open formats of such a tag are equivalent to an inline expression and the ``<%call>`` tag, respectively. .. sourcecode:: mako <%mynamespace:somedef param="some value"> this is the body To create custom tags which accept a body, see :ref:`defs_with_content`. .. versionadded:: 0.2.3 ``<%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>`` ---------- The ``%doc`` tag handles multiline comments: .. sourcecode:: mako <%doc> these are comments more comments Also the ``##`` symbol as the first non-space characters on a line can be used for single line comments. ``<%text>`` ----------- This tag suspends the Mako lexer's normal parsing of Mako template directives, and returns its entire body contents as plain text. It is used pretty much to write documentation about Mako: .. sourcecode:: mako <%text filter="h"> heres some fake mako ${syntax} <%def name="x()">${x} .. _syntax_exiting_early: Exiting Early from a Template ============================= Sometimes you want to stop processing a template or ``<%def>`` method in the middle and just use the text you've accumulated so far. This is accomplished by using ``return`` statement inside a Python block. It's a good idea for the ``return`` statement to return an empty string, which prevents the Python default return value of ``None`` from being rendered by the template. This return value is for semantic purposes provided in templates via the ``STOP_RENDERING`` symbol: .. sourcecode:: mako % if not len(records): No records found. <% return STOP_RENDERING %> % endif Or perhaps: .. sourcecode:: mako <% if not len(records): return STOP_RENDERING %> In older versions of Mako, an empty string can be substituted for the ``STOP_RENDERING`` symbol: .. sourcecode:: mako <% return '' %> .. versionadded:: 1.0.2 - added the ``STOP_RENDERING`` symbol which serves as a semantic identifier for the empty string ``""`` used by a Python ``return`` statement. Mako-1.0.3/doc/build/templates/0000755000076500000240000000000012613724373017020 5ustar classicstaff00000000000000Mako-1.0.3/doc/build/templates/base.mako0000644000076500000240000000267612613724132020607 0ustar classicstaff00000000000000 <%block name="head_title">Mako Templates for Python</%block> % for cssfile in self.attr.default_css_files + css_files: % endfor <%block name="headers">

${next.body()}
<%block name="footer">
Mako-1.0.3/doc/build/templates/genindex.mako0000644000076500000240000000351512613724132021467 0ustar classicstaff00000000000000<%inherit file="${context['layout']}"/> <%block name="show_title" filter="util.striptags"> ${_('Index')}

${_('Index')}

% for i, (key, dummy) in enumerate(genindexentries): ${i != 0 and '| ' or ''}${key} % endfor
% for i, (key, entries) in enumerate(genindexentries):

${key}

<% breakat = genindexcounts[i] // 2 numcols = 1 numitems = 0 %> % for entryname, (links, subitems) in entries:
% if links: ${entryname|h} % for unknown, link in links[1:]: , [${i}] % endfor % else: ${entryname|h} % endif
% if subitems:
% for subentryname, subentrylinks in subitems:
${subentryname|h} % for j, (unknown, link) in enumerate(subentrylinks[1:]): [${j}] % endfor
% endfor
% endif <% numitems = numitems + 1 + len(subitems) %> % if numcols <2 and numitems > breakat: <% numcols = numcols + 1 %>
% endif % endfor
% endfor <%def name="sidebarrel()"> % if split_index:

${_('Index')}

% for i, (key, dummy) in enumerate(genindexentries): ${i > 0 and '| ' or ''} ${key} % endfor

${_('Full index on one page')}

% endif ${parent.sidebarrel()} Mako-1.0.3/doc/build/templates/layout.mako0000644000076500000240000001333412613724132021203 0ustar classicstaff00000000000000## coding: utf-8 <%! local_script_files = [] default_css_files = [ '_static/pygments.css', '_static/docs.css', '_static/site.css' ] %> <%doc> Structural elements are all prefixed with "docs-" to prevent conflicts when the structure is integrated into the main site. docs-container -> docs-header -> docs-search docs-version-header docs-top-navigation docs-top-page-control docs-navigation-banner docs-body-container -> docs-sidebar docs-body docs-bottom-navigation docs-copyright <%inherit file="base.mako"/> <% withsidebar = bool(toc) and current_page_name != 'index' %> <%block name="head_title"> % if current_page_name != 'index': ${capture(self.show_title) | util.striptags} — % endif ${docstitle|h}
<%block name="headers"> ${parent.headers()} % for scriptfile in script_files + self.attr.local_script_files: % endfor % if hasdoc('about'): % endif % if hasdoc('copyright'): % endif % if parents: % endif % if nexttopic: % endif % if prevtopic: % endif

${docstitle|h}

Release: ${release}
${docstitle|h} % if parents: % for parent in parents: » ${parent['title']} % endfor % endif % if current_page_name != 'index': » ${self.show_title()} % endif

<%block name="show_title"> ${title}

% if withsidebar:

Table of Contents

${toc} % if prevtopic:

Previous Topic

${prevtopic['title']}

% endif % if nexttopic:

Next Topic

${nexttopic['title']}

% endif

Quick Search

% endif
${next.body()}
Mako-1.0.3/doc/build/templates/page.mako0000644000076500000240000000011412613724132020572 0ustar classicstaff00000000000000<%inherit file="${context['layout']}"/> ${body| util.strip_toplevel_anchors}Mako-1.0.3/doc/build/templates/rtd_layout.mako0000644000076500000240000000160112613724132022046 0ustar classicstaff00000000000000 <%inherit file="/layout.mako"/> <%block name="headers"> ${parent.headers()} ${next.body()} <%block name="footer"> ${parent.footer()} Mako-1.0.3/doc/build/templates/search.mako0000644000076500000240000000124012613724132021124 0ustar classicstaff00000000000000<%inherit file="${context['layout']}"/> <%! local_script_files = ['_static/searchtools.js'] %> <%block name="show_title" filter="util.striptags"> ${_('Search')}

Enter Search Terms:

<%block name="footer"> ${parent.footer()} Mako-1.0.3/doc/build/unicode.rst0000644000076500000240000003247312613724132017204 0ustar classicstaff00000000000000.. _unicode_toplevel: =================== The Unicode Chapter =================== The Python language supports two ways of representing what we know as "strings", i.e. series of characters. In Python 2, the two types are ``string`` and ``unicode``, and in Python 3 they are ``bytes`` and ``string``. A key aspect of the Python 2 ``string`` and Python 3 ``bytes`` types are that they contain no information regarding what **encoding** the data is stored in. For this reason they were commonly referred to as **byte strings** on Python 2, and Python 3 makes this name more explicit. The origins of this come from Python's background of being developed before the Unicode standard was even available, back when strings were C-style strings and were just that, a series of bytes. Strings that had only values below 128 just happened to be **ASCII** strings and were printable on the console, whereas strings with values above 128 would produce all kinds of graphical characters and bells. Contrast the "byte-string" type with the "unicode/string" type. Objects of this latter type are created whenever you say something like ``u"hello world"`` (or in Python 3, just ``"hello world"``). In this case, Python represents each character in the string internally using multiple bytes per character (something similar to UTF-16). What's important is that when using the ``unicode``/``string`` type to store strings, Python knows the data's encoding; it's in its own internal format. Whereas when using the ``string``/``bytes`` type, it does not. When Python 2 attempts to treat a byte-string as a string, which means it's attempting to compare/parse its characters, to coerce it into another encoding, or to decode it to a unicode object, it has to guess what the encoding is. In this case, it will pretty much always guess the encoding as ``ascii``... and if the byte-string contains bytes above value 128, you'll get an error. Python 3 eliminates much of this confusion by just raising an error unconditionally if a byte-string is used in a character-aware context. There is one operation that Python *can* do with a non-ASCII byte-string, and it's a great source of confusion: it can dump the byte-string straight out to a stream or a file, with nary a care what the encoding is. To Python, this is pretty much like dumping any other kind of binary data (like an image) to a stream somewhere. In Python 2, it is common to see programs that embed all kinds of international characters and encodings into plain byte-strings (i.e. using ``"hello world"`` style literals) can fly right through their run, sending reams of strings out to wherever they are going, and the programmer, seeing the same output as was expressed in the input, is now under the illusion that his or her program is Unicode-compliant. In fact, their program has no unicode awareness whatsoever, and similarly has no ability to interact with libraries that *are* unicode aware. Python 3 makes this much less likely by defaulting to unicode as 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`` 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 unicode strings and other kinds of encoding conversions more intelligently, the usage of raw byte-strings quickly becomes a nightmare, since you are sending the Python interpreter collections of bytes for which it can make no intelligent decisions with regards to encoding. In Python 3 Mako only allows usage of native, unicode strings. In normal Mako operation, all parsed template constructs and 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 :ref:`the encoding of all non-ASCII templates is explicit ` (still required in Python 3), that :ref:`all non-ASCII-encoded expressions are in one way or another converted to unicode ` (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). .. _set_template_file_encoding: Specifying the Encoding of a Template File ========================================== This is the most basic encoding-related setting, and it is equivalent to Python's "magic encoding comment", as described in `pep-0263 `_. Any template that contains non-ASCII characters requires that this comment be present so that Mako can decode to unicode (and also make usage of Python's AST parsing services). Mako's lexer will use this encoding in order to convert the template source into a ``unicode`` object before continuing its parsing: .. sourcecode:: mako ## -*- coding: utf-8 -*- Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! » For the picky, the regular expression used is derived from that of the above mentioned pep: .. sourcecode:: python #.*coding[:=]\s*([-\w.]+).*\n The lexer will convert to unicode in all cases, so that if any characters exist in the template that are outside of the specified encoding (or the default of ``ascii``), the error will be immediate. As an alternative, the template encoding can be specified programmatically to either :class:`.Template` or :class:`.TemplateLookup` via the ``input_encoding`` parameter: .. sourcecode:: python t = TemplateLookup(directories=['./'], input_encoding='utf-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 ==================== The next area that encoding comes into play is in expression constructs. By default, Mako's treatment of an expression like this: .. sourcecode:: mako ${"hello world"} looks something like this: .. sourcecode:: python context.write(unicode("hello world")) In Python 3, it's just: .. sourcecode:: python context.write(str("hello world")) That is, **the output of all expressions is run through the ``unicode`` built-in**. This is the default setting, and can be modified to expect various encodings. The ``unicode`` step serves both the purpose of rendering non-string expressions into strings (such as integers or objects which contain ``__str()__`` methods), and to ensure that the final output stream is constructed as a unicode object. The main implication of this is that **any raw byte-strings that contain an encoding other than ASCII must first be decoded to a Python unicode object**. It means you can't say this in Python 2: .. sourcecode:: mako ${"voix m’a réveillé."} ## error in Python 2! You must instead say this: .. sourcecode:: mako ${u"voix m’a réveillé."} ## OK ! Similarly, if you are reading data from a file that is streaming bytes, or returning data from some object that is returning a Python byte-string containing a non-ASCII encoding, you have to explicitly decode to unicode first, such as: .. sourcecode:: mako ${call_my_object().decode('utf-8')} Note that filehandles acquired by ``open()`` in Python 3 default to returning "text", that is the decoding is done for you. See Python 3's documentation for the ``open()`` built-in for details on this. If you want a certain encoding applied to *all* expressions, override the ``unicode`` builtin with the ``decode`` built-in at the :class:`.Template` or :class:`.TemplateLookup` level: .. sourcecode:: python t = Template(templatetext, default_filters=['decode.utf8']) Note that the built-in ``decode`` object is slower than the ``unicode`` function, since unlike ``unicode`` it's not a Python built-in, and it also checks the type of the incoming data to determine if string conversion is needed first. 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 ======================== 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 :doc:`"Usage" chapter `, 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: .. sourcecode:: python 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()) :meth:`~.Template.render` will return a ``bytes`` object in Python 3 if an output encoding is specified. By default it performs no encoding and returns a native string. :meth:`~.Template.render_unicode` will return the template output as a Python ``unicode`` object (or ``string`` in Python 3): .. sourcecode:: python print(mytemplate.render_unicode()) The above method disgards the output encoding keyword argument; you can encode yourself by saying: .. sourcecode:: python print(mytemplate.render_unicode().encode('utf-8', 'replace')) Buffer Selection ---------------- Mako does play some games with the style of buffering used internally, to maximize performance. Since the buffer is by far the most heavily used object in a render operation, it's important! When calling :meth:`~.Template.render` on a template that does not specify any output encoding (i.e. it's ``ascii``), Python's ``cStringIO`` module, which cannot handle encoding of non-ASCII ``unicode`` objects (even though it can send raw byte-strings through), is used for buffering. Otherwise, a custom Mako class called ``FastEncodingBuffer`` is used, which essentially is a super dumbed-down version of ``StringIO`` that gathers all strings into a list and uses ``u''.join(elements)`` to produce the final output -- it's markedly faster than ``StringIO``. .. _unicode_disabled: Saying to Heck with It: Disabling the Usage of Unicode Entirely =============================================================== Some segments of Mako's userbase choose to make no usage of Unicode whatsoever, and instead would prefer the "pass through" approach; all string expressions in their templates return encoded byte-strings, and they would like these strings to pass right through. The only advantage to this approach is that templates need not use ``u""`` for literal strings; there's an arguable speed improvement as well since raw byte-strings generally perform slightly faster than unicode objects in Python. For these users, assuming they're sticking with Python 2, they can hit the ``disable_unicode=True`` flag as so: .. sourcecode:: python # -*- coding:utf-8 -*- from mako.template import Template t = Template("drôle de petite voix m’a réveillé.", disable_unicode=True, input_encoding='utf-8') print(t.code) The ``disable_unicode`` mode is strictly a Python 2 thing. It is not supported at all in Python 3. The generated module source code will contain elements like these: .. sourcecode:: python # -*- coding:utf-8 -*- # ...more generated code ... def render_body(context,**pageargs): context.caller_stack.push_frame() try: __M_locals = dict(pageargs=pageargs) # SOURCE LINE 1 context.write('dr\xc3\xb4le de petite voix m\xe2\x80\x99a r\xc3\xa9veill\xc3\xa9.') return '' finally: context.caller_stack.pop_frame() Where above that the string literal used within :meth:`.Context.write` 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 ``[]`` 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. This because MarkupSafe only supports Python unicode objects for non-ASCII strings. .. versionchanged:: 0.3.4 In prior versions, it used ``cgi.escape()``, which has been replaced with a function that also escapes single quotes. 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. * Don't use this option just because you don't want to learn to use Unicode properly; we aren't supporting user issues in this mode of operation. We will however offer generous help for the vast majority of users who stick to the Unicode program. * Python 3 is unicode by default, and the flag is not available when running on Python 3. Mako-1.0.3/doc/build/usage.rst0000644000076500000240000004266712613724132016670 0ustar classicstaff00000000000000.. _usage_toplevel: ===== 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, :ref:`syntax_toplevel`. The most basic way to create a template and render it is through the :class:`.Template` class: .. sourcecode:: python 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 ``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 ``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: .. sourcecode:: python 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: .. sourcecode:: python 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 :class:`.Template` can also load its template source code from a file, using the ``filename`` keyword argument: .. sourcecode:: python from mako.template import Template mytemplate = Template(filename='/docs/mytmpl.txt') print(mytemplate.render()) For improved performance, a :class:`.Template` which is loaded from a file can also cache the source code to its generated module on the filesystem as a regular Python module file (i.e. a ``.py`` file). To do this, just add the ``module_directory`` argument to the template: .. sourcecode:: python 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 :class:`.Template` with the same arguments is created, this module file will be automatically re-used. .. _usage_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 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 :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: .. sourcecode:: python 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 :class:`.TemplateLookup` object to it, which will search in the directory ``/docs`` for the file ``"header.txt"``. Usually, an application will store most or all of its templates as text files on the filesystem. So far, all of our examples have been a little bit contrived in order to illustrate the basic concepts. But a real application would get most or all of its templates directly from the :class:`.TemplateLookup`, using the aptly named :meth:`~.TemplateLookup.get_template` method, which accepts the URI of the desired template: .. sourcecode:: python 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 :class:`.TemplateLookup` which will look for templates in the ``/docs`` directory, and will store generated module files in the ``/tmp/mako_modules`` directory. The lookup locates templates by appending the given URI to each of its search directories; so if you gave it a URI of ``/etc/beans/info.txt``, it would search for the file ``/docs/etc/beans/info.txt``, else raise a :class:`.TopLevelNotFound` exception, which is a custom Mako exception. When the lookup locates templates, it will also assign a ``uri`` property to the :class:`.Template` which is the URI passed to the :meth:`~.TemplateLookup.get_template()` call. :class:`.Template` uses this URI to calculate the name of its module file. So in the above example, a ``templatename`` argument of ``/etc/beans/info.txt`` will create a module file ``/tmp/mako_modules/etc/beans/info.txt.py``. Setting the Collection Size --------------------------- The :class:`.TemplateLookup` also serves the important need of caching a fixed set of templates in memory at a given time, so that successive URI lookups do not result in full template compilations and/or module reloads on each request. By default, the :class:`.TemplateLookup` size is unbounded. You can specify a fixed size using the ``collection_size`` argument: .. sourcecode:: python 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 :class:`.TemplateLookup` is ``filesystem_checks``. This defaults to ``True``, and says that each time a template is returned by the :meth:`~.TemplateLookup.get_template()` method, the revision time of the original template file is checked against the last time the template was loaded, and if the file is newer will reload its contents and recompile the template. On a production system, setting ``filesystem_checks`` to ``False`` can afford a small to moderate performance increase (depending on the type of filesystem used). .. _usage_unicode: 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: .. sourcecode:: python 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 :meth:`~.Template.render` method will return a ``bytes`` object, **if** ``output_encoding`` is set. Otherwise it returns a ``string``. Additionally, the :meth:`~.Template.render_unicode()` method exists which will return the template output as a Python ``unicode`` object, or in Python 3 a ``string``: .. sourcecode:: python print(mytemplate.render_unicode()) The above method disregards the output encoding keyword argument; you can encode yourself by saying: .. sourcecode:: python 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 :ref:`unicode_toplevel`. .. _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 :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: .. sourcecode:: python 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: .. sourcecode:: python from mako import exceptions try: template = lookup.get_template(uri) print(template.render()) except: print(exceptions.html_error_template().render()) The :func:`.html_error_template` template accepts two options: specifying ``full=False`` causes only a section of an HTML document to be rendered. Specifying ``css=False`` will disable the default stylesheet from being rendered. E.g.: .. sourcecode:: python print(exceptions.html_error_template().render(full=False)) 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`: .. sourcecode:: python 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 :class:`.Template` itself, and no output stream is defined. Therefore exceptions which occur within the lookup/parse/compile stage will not be handled and will propagate normally. While the pre-render traceback usually will not include any Mako-specific lines anyway, it will mean that exceptions which occur previous to rendering and those which occur within rendering will be handled differently... so the ``try``/``except`` patterns described previously are probably of more 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: .. sourcecode:: python 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)) 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 what's included. WSGI ---- A sample WSGI application is included in the distribution 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 :class:`.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 :mod:`mako.ext.pygmentplugin`. This module is used in the generation of Mako documentation and also contains various `setuptools` entry points under the heading ``pygments.lexers``, including ``mako``, ``html+mako``, ``xml+mako`` (see the ``setup.py`` file for all the entry points). 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, including those of control lines and expressions embedded in tags. `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``: .. sourcecode:: mako
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``): .. sourcecode:: 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 :class:`.Template`/:class:`.TemplateLookup`'s ``input_encoding`` parameter). Invoking `Babel`_'s extractor at the 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: .. sourcecode:: pot #. 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')}
See the `Babel User Guide `_ for more information. .. _babel: http://babel.edgewall.org/ API Reference ============= .. autoclass:: mako.template.Template :show-inheritance: :members: .. autoclass:: mako.template.DefTemplate :show-inheritance: :members: .. autoclass:: mako.lookup.TemplateCollection :show-inheritance: :members: .. autoclass:: mako.lookup.TemplateLookup :show-inheritance: :members: .. autoclass:: mako.exceptions.RichTraceback :show-inheritance: .. py:attribute:: error the exception instance. .. py:attribute:: message the exception error message as unicode. .. py:attribute:: source source code of the file where the error occurred. If the error occurred within a compiled template, this is the template source. .. py:attribute:: lineno line number where the error occurred. If the error occurred within a compiled template, the line number is adjusted to that of the template source. .. py:attribute:: 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``). .. py:attribute:: 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. .. py:attribute:: reverse_traceback the traceback list in reverse. .. autofunction:: mako.exceptions.html_error_template .. autofunction:: mako.exceptions.text_error_template Mako-1.0.3/examples/0000755000076500000240000000000012613724373014774 5ustar classicstaff00000000000000Mako-1.0.3/examples/bench/0000755000076500000240000000000012613724373016053 5ustar classicstaff00000000000000Mako-1.0.3/examples/bench/basic.py0000644000076500000240000001540112613724132017500 0ustar classicstaff00000000000000# basic.py - basic benchmarks adapted from Genshi # Copyright (C) 2006 Edgewall Software # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from cgi import escape import os try: from StringIO import StringIO except ImportError: from io import StringIO import sys import timeit def u(stringlit): if sys.version_info >= (3,): return stringlit else: return stringlit.decode('latin1') __all__ = ['mako', 'mako_inheritance', 'jinja2', 'jinja2_inheritance', 'cheetah', 'django', 'myghty', 'genshi', 'kid'] # Templates content and constants TITLE = 'Just a test' USER = 'joe' ITEMS = ['Number %d' % num for num in range(1, 15)] U_ITEMS = [u(item) for item in ITEMS] def genshi(dirname, verbose=False): from genshi.template import TemplateLoader loader = TemplateLoader([dirname], auto_reload=False) template = loader.load('template.html') def render(): data = dict(title=TITLE, user=USER, items=ITEMS) return template.generate(**data).render('xhtml') if verbose: print(render()) return render def myghty(dirname, verbose=False): from myghty import interp interpreter = interp.Interpreter(component_root=dirname) def render(): data = dict(title=TITLE, user=USER, items=ITEMS) buffer = StringIO() interpreter.execute("template.myt", request_args=data, out_buffer=buffer) return buffer.getvalue() if verbose: print(render()) return render def mako(dirname, verbose=False): from mako.template import Template from mako.lookup import TemplateLookup disable_unicode = (sys.version_info < (3,)) lookup = TemplateLookup(directories=[dirname], filesystem_checks=False, disable_unicode=disable_unicode) template = lookup.get_template('template.html') def render(): return template.render(title=TITLE, user=USER, list_items=U_ITEMS) if verbose: print(template.code + " " + render()) return render mako_inheritance = mako def jinja2(dirname, verbose=False): from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader(dirname)) template = env.get_template('template.html') def render(): return template.render(title=TITLE, user=USER, list_items=U_ITEMS) if verbose: print(render()) return render jinja2_inheritance = jinja2 def cheetah(dirname, verbose=False): from Cheetah.Template import Template filename = os.path.join(dirname, 'template.tmpl') template = Template(file=filename) def render(): template.__dict__.update({'title': TITLE, 'user': USER, 'list_items': U_ITEMS}) return template.respond() if verbose: print(dir(template)) print(template.generatedModuleCode()) print(render()) return render def django(dirname, verbose=False): from django.conf import settings settings.configure(TEMPLATE_DIRS=[os.path.join(dirname, 'templates')]) from django import template, templatetags from django.template import loader templatetags.__path__.append(os.path.join(dirname, 'templatetags')) tmpl = loader.get_template('template.html') def render(): data = {'title': TITLE, 'user': USER, 'items': ITEMS} return tmpl.render(template.Context(data)) if verbose: print(render()) return render def kid(dirname, verbose=False): import kid kid.path = kid.TemplatePath([dirname]) template = kid.Template(file='template.kid') def render(): template = kid.Template(file='template.kid', title=TITLE, user=USER, items=ITEMS) return template.serialize(output='xhtml') if verbose: print(render()) return render def run(engines, number=2000, verbose=False): basepath = os.path.abspath(os.path.dirname(__file__)) for engine in engines: dirname = os.path.join(basepath, engine) if verbose: print('%s:' % engine.capitalize()) print('--------------------------------------------------------') else: sys.stdout.write('%s:' % engine.capitalize()) t = timeit.Timer(setup='from __main__ import %s; render = %s(r"%s", %s)' % (engine, engine, dirname, verbose), stmt='render()') time = t.timeit(number=number) / number if verbose: print('--------------------------------------------------------') print('%.2f ms' % (1000 * time)) if verbose: print('--------------------------------------------------------') if __name__ == '__main__': engines = [arg for arg in sys.argv[1:] if arg[0] != '-'] if not engines: engines = __all__ verbose = '-v' in sys.argv if '-p' in sys.argv: try: import hotshot, hotshot.stats prof = hotshot.Profile("template.prof") benchtime = prof.runcall(run, engines, number=100, verbose=verbose) stats = hotshot.stats.load("template.prof") except ImportError: import cProfile, pstats stmt = "run(%r, number=%r, verbose=%r)" % (engines, 1000, verbose) cProfile.runctx(stmt, globals(), {}, "template.prof") stats = pstats.Stats("template.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats() else: run(engines, verbose=verbose) Mako-1.0.3/examples/bench/cheetah/0000755000076500000240000000000012613724373017454 5ustar classicstaff00000000000000Mako-1.0.3/examples/bench/cheetah/footer.tmpl0000644000076500000240000000003112613724132021633 0ustar classicstaff00000000000000 Mako-1.0.3/examples/bench/cheetah/header.tmpl0000644000076500000240000000005512613724132021573 0ustar classicstaff00000000000000 Mako-1.0.3/examples/bench/cheetah/template.tmpl0000644000076500000240000000124612613724132022161 0ustar classicstaff00000000000000 ${title} #def greeting(name)

hello ${name}!

#end def #include "cheetah/header.tmpl" $greeting($user) $greeting('me') $greeting('world')

Loop

#if $list_items
    #for $list_item in $list_items
  • $list_item
  • #end for
#end if #include "cheetah/footer.tmpl" Mako-1.0.3/examples/bench/django/0000755000076500000240000000000012613724373017315 5ustar classicstaff00000000000000Mako-1.0.3/examples/bench/django/templatetags/0000755000076500000240000000000012613724373022007 5ustar classicstaff00000000000000Mako-1.0.3/examples/bench/django/templatetags/__init__.py0000644000076500000240000000000012613724132024077 0ustar classicstaff00000000000000Mako-1.0.3/examples/bench/django/templatetags/bench.py0000644000076500000240000000033412613724132023431 0ustar classicstaff00000000000000from django.template import Library, Node, resolve_variable from django.utils.html import escape register = Library() def greeting(name): return 'Hello, %s!' % escape(name) greeting = register.simple_tag(greeting) Mako-1.0.3/examples/bench/kid/0000755000076500000240000000000012613724373016622 5ustar classicstaff00000000000000Mako-1.0.3/examples/bench/kid/base.kid0000644000076500000240000000052012613724132020213 0ustar classicstaff00000000000000

Hello, ${name}!

${item}