mako-1.3.2/0000755000175000017500000000000014556174701011532 5ustar piotrpiotrmako-1.3.2/.github/0000755000175000017500000000000014556174701013072 5ustar piotrpiotrmako-1.3.2/.github/FUNDING.yml0000644000175000017500000000015714556174701014712 0ustar piotrpiotr# These are supported funding model platforms github: sqlalchemy patreon: zzzeek tidelift: "pypi/SQLAlchemy" mako-1.3.2/.github/workflows/0000755000175000017500000000000014556174701015127 5ustar piotrpiotrmako-1.3.2/.github/workflows/run-on-pr.yaml0000644000175000017500000000214114556174701017646 0ustar piotrpiotrname: Run tests on a pr on: # run on pull request to main excluding changes that are only on doc or example folders pull_request: branches: - main paths-ignore: - "doc/**" jobs: run-test: name: ${{ matrix.python-version }}-${{ matrix.os }}-${{matrix.tox-env}} runs-on: ${{ matrix.os }} strategy: # run this job using this matrix matrix: os: - "ubuntu-latest" python-version: - "3.10" tox-env: - "" - "-e pep8" fail-fast: false # steps to run in each job. Some are github actions, others run shell commands steps: - name: Checkout repo uses: actions/checkout@v4 - name: Set up python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} architecture: ${{ matrix.architecture }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install --upgrade tox setuptools pip list - name: Run tests run: tox ${{ matrix.tox-env }} mako-1.3.2/.github/workflows/run-test.yaml0000644000175000017500000000271114556174701017575 0ustar piotrpiotrname: Run tests on: # run on push in main or rel_* branches excluding changes are only on doc or example folders push: branches: - main - "rel_*" # branches used to test the workflow - "workflow_test_*" paths-ignore: - "docs/**" jobs: run-test: name: ${{ matrix.python-version }}-${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: # run this job using this matrix matrix: os: - "ubuntu-latest" - "windows-latest" - "macos-latest" python-version: - "3.8" - "3.9" - "3.10" - "3.11" - "3.12" exclude: # beaker raises warning on 3.10. only windows seems affected # See https://github.com/bbangert/beaker/pull/213 - os: "windows-latest" python-version: "3.10" fail-fast: false # steps to run in each job. Some are github actions, others run shell commands steps: - name: Checkout repo uses: actions/checkout@v4 - name: Set up python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} allow-prereleases: true architecture: ${{ matrix.architecture }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install --upgrade tox setuptools pip list - name: Run tests run: tox mako-1.3.2/.gitignore0000644000175000017500000000020314556174701013515 0ustar piotrpiotr/build /dist /.coverage /doc/build/output *.pyc *.orig *.egg-info *.sw[opq] /.Python /bin /include /lib /man .tox/ .cache/ .vscode mako-1.3.2/.gitreview0000644000175000017500000000011714556174701013537 0ustar piotrpiotr[gerrit] host=gerrit.sqlalchemy.org project=sqlalchemy/mako defaultbranch=main mako-1.3.2/.pre-commit-config.yaml0000644000175000017500000000045614556174701016020 0ustar piotrpiotr# See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/python/black rev: 23.9.1 hooks: - id: black - repo: https://github.com/sqlalchemyorg/zimports rev: v0.6.0 hooks: - id: zimports mako-1.3.2/AUTHORS0000644000175000017500000000043214556174701012601 0ustar piotrpiotrMako was created by Michael Bayer. Major contributing authors include: - Michael Bayer - Geoffrey T. Dairiki - Philip Jenvey - David Peckam - Armin Ronacher - Ben Bangert - Ben Trofatter mako-1.3.2/CHANGES0000644000175000017500000000026314556174701012526 0ustar piotrpiotr===== 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.3.2/LICENSE0000644000175000017500000000211214556174701012533 0ustar piotrpiotrCopyright 2006-2024 the Mako authors and contributors . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mako-1.3.2/MANIFEST.in0000644000175000017500000000041214556174701013265 0ustar piotrpiotrrecursive-include doc *.html *.css *.txt *.js *.png *.py Makefile *.rst *.mako recursive-include examples *.py *.xml *.mako *.myt *.kid *.tmpl recursive-include test *.py *.html *.mako *.cfg include README* AUTHORS LICENSE CHANGES* tox.ini prune doc/build/output mako-1.3.2/README.rst0000644000175000017500000000266314556174701013230 0ustar piotrpiotr========================= Mako Templates for Python ========================= Mako is a template library written in Python. It provides a familiar, non-XML syntax which compiles into Python modules for maximum performance. Mako's syntax and API borrows from the best ideas of many others, including Django templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded Python (i.e. Python Server Page) language, which refines the familiar ideas of componentized layout and inheritance to produce one of the most straightforward and flexible models available, while also maintaining close ties to Python calling and scoping semantics. Nutshell ======== :: <%inherit file="base.html"/> <% rows = [[v for v in range(0,10)] for row in range(0,10)] %> % for row in rows: ${makerow(row)} % endfor
<%def name="makerow(row)"> % for name in row: ${name}\ % endfor Philosophy =========== Python is a great scripting language. Don't reinvent the wheel...your templates can handle it ! Documentation ============== See documentation for Mako at https://docs.makotemplates.org/en/latest/ License ======== Mako is licensed under an MIT-style license (see LICENSE). Other incorporated projects may be licensed under different licenses. All licenses allow for non-commercial and commercial use. mako-1.3.2/doc/0000755000175000017500000000000014556174701012277 5ustar piotrpiotrmako-1.3.2/doc/build/0000755000175000017500000000000014556174701013376 5ustar piotrpiotrmako-1.3.2/doc/build/Makefile0000644000175000017500000001137714556174701015047 0ustar piotrpiotr# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = -T 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.3.2/doc/build/caching.rst0000644000175000017500000003255414556174701015535 0ustar piotrpiotr.. _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 ``importlib.metatada`` 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.3.2/doc/build/changelog.rst0000644000175000017500000020653614556174701016073 0ustar piotrpiotr ========= Changelog ========= 1.3 === .. changelog:: :version: 1.3.2 :released: Tue Jan 30 2024 .. change:: :tags: bug, lexer :tickets: 323 Fixed parsing issue where attempting to render a single percent sign % using an escaped percent %% would not function correctly if the escaped percent were not the first character on a line. Note that this is a revised version of a similar change made in Mako 1.3.1 which caused unexpected parsing regressions, resulting in the release being yanked. Pull request courtesy Hai Zhu. .. changelog:: :version: 1.3.1 :released: Mon Jan 22 2024 .. change:: :tags: bug, lexer :tickets: 323 Fixed parsing issue where attempting to render a single percent sign ``%`` using an escaped percent ``%%`` would not function correctly if the escaped percent were not the first character on a line. Pull request courtesy Hai Zhu. .. note:: Mako 1.3.1 was yanked from pypi and this change was reverted, replaced with a modified version for Mako 1.3.2. .. changelog:: :version: 1.3.0 :released: Wed Nov 8 2023 .. change:: :tags: change, installation Mako 1.3.0 bumps the minimum Python version to 3.8, as 3.7 is EOL as of 2023-06-27. Python 3.12 is now supported explicitly. 1.2 === .. changelog:: :version: 1.2.4 :released: Tue Nov 15 2022 .. change:: :tags: bug, codegen :tickets: 368 Fixed issue where unpacking nested tuples in a for loop using would raise a "couldn't apply loop context" error if the loop context was used. The regex used to match the for loop expression now allows the list of loop variables to contain parenthesized sub-tuples. Pull request courtesy Matt Trescott. .. changelog:: :version: 1.2.3 :released: Thu Sep 22 2022 .. change:: :tags: bug, lexer :tickets: 367 Fixed issue in lexer in the same category as that of :ticket:`366` where the regexp used to match an end tag didn't correctly organize for matching characters surrounded by whitespace, leading to high memory / interpreter hang if a closing tag incorrectly had a large amount of unterminated space in it. Credit to Sebastian Chnelik for locating the issue. As Mako templates inherently render and directly invoke arbitrary Python code from the template source, it is **never** appropriate to create templates that contain untrusted input. .. changelog:: :version: 1.2.2 :released: Mon Aug 29 2022 .. change:: :tags: bug, lexer :tickets: 366 Fixed issue in lexer where the regexp used to match tags would not correctly interpret quoted sections individually. While this parsing issue still produced the same expected tag structure later on, the mis-handling of quoted sections was also subject to a regexp crash if a tag had a large number of quotes within its quoted sections. Credit to Sebastian Chnelik for locating the issue. As Mako templates inherently render and directly invoke arbitrary Python code from the template source, it is **never** appropriate to create templates that contain untrusted input. .. changelog:: :version: 1.2.1 :released: Thu Jun 30 2022 .. change:: :tags: performance :tickets: 361 Optimized some codepaths within the lexer/Python code generation process, improving performance for generation of templates prior to their being cached. Pull request courtesy Takuto Ikuta. .. change:: :tags: bug, tests :tickets: 360 Various fixes to the test suite in the area of exception message rendering to accommodate for variability in Python versions as well as Pygments. .. changelog:: :version: 1.2.0 :released: Thu Mar 10 2022 .. change:: :tags: changed, py3k :tickets: 351 Corrected "universal wheel" directive in ``setup.cfg`` so that building a wheel does not target Python 2. .. change:: :tags: changed, py3k The ``bytestring_passthrough`` template argument is removed, as this flag only applied to Python 2. .. change:: :tags: changed, py3k With the removal of Python 2's ``cStringIO``, Mako now uses its own internal ``FastEncodingBuffer`` exclusively. .. change:: :tags: changed, py3k Removed ``disable_unicode`` flag, that's no longer used in Python 3. .. change:: :tags: changed :tickets: 349 Refactored test utilities into ``mako.testing`` module. Removed ``unittest.TestCase`` dependency in favor of ``pytest``. .. change:: :tags: changed, setup Replaced the use of ``pkg_resources`` with the ``importlib`` library. For Python < 3.8 the library ``importlib_metadata`` is used. .. change:: :tags: changed, py3k Removed support for Python 2 and Python 3.6. Mako now requires Python >= 3.7. .. change:: :tags: bug, py3k Mako now performs exception chaining using ``raise from``, correctly identifying underlying exception conditions when it raises its own exceptions. Pull request courtesy Ram Rachum. 1.1 === .. changelog:: :version: 1.1.6 :released: Wed Nov 17 2021 .. change:: :tags: bug, lexer :tickets: 346 :versions: 1.2.0, 1.1.6 Fixed issue where control statements on multi lines with a backslash would not parse correctly if the template itself contained CR/LF pairs as on Windows. Pull request courtesy Charles Pigott. .. changelog:: :version: 1.1.5 :released: Fri Aug 20 2021 .. change:: :tags: bug, tests :tickets: 338 Fixed some issues with running the test suite which would be revealed by running tests in random order. .. changelog:: :version: 1.1.4 :released: Thu Jan 14 2021 .. change:: :tags: bug, py3k :tickets: 328 Fixed Python deprecation issues related to module importing, as well as file access within the Lingua plugin, for deprecated APIs that began to emit warnings under Python 3.10. Pull request courtesy Petr Viktorin. .. changelog:: :version: 1.1.3 :released: Fri May 29 2020 .. change:: :tags: bug, templates :tickets: 267 The default template encoding is now utf-8. Previously, the encoding was "ascii", which was standard throughout Python 2. This allows that "magic encoding comment" for utf-8 templates is no longer required. .. changelog:: :version: 1.1.2 :released: Sun Mar 1 2020 .. change:: :tags: feature, commands :tickets: 283 Added --output-file argument to the Mako command line runner, which allows a specific output file to be selected. Pull request courtesy Björn Dahlgren. .. changelog:: :version: 1.1.1 :released: Mon Jan 20 2020 .. change:: :tags: bug, py3k :tickets: 310 Replaced usage of the long-superseded "parser.suite" module in the mako.util package for parsing the python magic encoding comment with the "ast.parse" function introduced many years ago in Python 2.5, as "parser.suite" is emitting deprecation warnings in Python 3.9. .. change:: :tags: bug, ext :tickets: 304 Added "babel" and "lingua" dependency entries to the setuptools entrypoints for the babel and lingua extensions, so that pkg_resources can check that these extra dependencies are available, raising an informative exception if not. Pull request courtesy sinoroc. .. changelog:: :version: 1.1.0 :released: Thu Aug 1 2019 .. change:: :tags: bug, py3k, windows :tickets: 301 Replaced usage of time.clock() on windows as well as time.time() elsewhere for microsecond timestamps with timeit.default_timer(), as time.clock() is being removed in Python 3.8. Pull request courtesy Christoph Reiter. .. change:: :tags: bug, py3k :tickets: 295 Replaced usage of ``inspect.getfullargspec()`` with the vendored version used by SQLAlchemy, Alembic to avoid future deprecation warnings. Also cleans up an additional version of the same function that's apparently been floating around for some time. .. change:: :tags: changed, setup :tickets: 303 Removed the "python setup.py test" feature in favor of a straight run of "tox". Per Pypa / pytest developers, "setup.py" commands are in general headed towards deprecation in favor of tox. The tox.ini script has been updated such that running "tox" with no arguments will perform a single run of the test suite against the default installed Python interpreter. .. seealso:: https://github.com/pypa/setuptools/issues/1684 https://github.com/pytest-dev/pytest/issues/5534 .. change:: :tags: changed, py3k, installer :tickets: 249 Mako 1.1 now supports Python versions: * 2.7 * 3.4 and higher This includes that setup.py no longer includes any conditionals, allowing for a pure Python wheel build, however this is not necessarily part of the Pypi release process as of yet. The test suite also raises for Python deprecation warnings. 1.0 === .. changelog:: :version: 1.0.14 :released: Sat Jul 20 2019 .. change:: :tags: feature, template The ``n`` filter is now supported in the ``<%page>`` tag. This allows a template to omit the default expression filters throughout a whole template, for those cases where a template-wide filter needs to have default filtering disabled. Pull request courtesy Martin von Gagern. .. seealso:: :ref:`expression_filtering_nfilter` .. change:: :tags: bug, exceptions Fixed issue where the correct file URI would not be shown in the template-formatted exception traceback if the template filename were not known. Additionally fixes an issue where stale filenames would be displayed if a stack trace alternated between different templates. Pull request courtesy Martin von Gagern. .. changelog:: :version: 1.0.13 :released: Mon Jul 1 2019 .. change:: :tags: bug, exceptions Improved the line-number tracking for source lines inside of Python ``<% ... %>`` blocks, such that text- and HTML-formatted exception traces such as that of :func:`.html_error_template` now report the correct source line inside the block, rather than the first line of the block itself. Exceptions in ``<%! ... %>`` blocks which get raised while loading the module are still not reported correctly, as these are handled before the Mako code is generated. Pull request courtesy Martin von Gagern. .. changelog:: :version: 1.0.12 :released: Wed Jun 5 2019 .. change:: :tags: bug, py3k :tickets: 296 Fixed regression where import refactors in Mako 1.0.11 caused broken imports on Python 3.8. .. changelog:: :version: 1.0.11 :released: Fri May 31 2019 .. change:: :tags: changed Updated for additional project metadata in setup.py. Additionally, the code has been reformatted using Black and zimports. .. changelog:: :version: 1.0.10 :released: Fri May 10 2019 .. change:: :tags: bug, py3k :tickets: 293 Added a default encoding of "utf-8" when the :class:`.RichTraceback` object retrieves Python source lines from a Python traceback; as these are bytes in Python 3 they need to be decoded so that they can be formatted in the template. .. changelog:: :version: 1.0.9 :released: Mon Apr 15 2019 .. change:: :tags: bug :tickets: 287 Further corrected the previous fix for :ticket:`287` as it relied upon an attribute that is monkeypatched by Python's ``ast`` module for some reason, which fails if ``ast`` hasn't been imported; the correct attribute ``Constant.value`` is now used. Also note the issue was mis-numbered in the previous changelog note. .. changelog:: :version: 1.0.8 :released: Wed Mar 20 2019 :released: Wed Mar 20 2019 .. change:: :tags: bug :tickets: 287 Fixed an element in the AST Python generator which changed for Python 3.8, causing expression generation to fail. .. change:: :tags: feature :tickets: 271 Added ``--output-encoding`` flag to the mako-render script. Pull request courtesy lacsaP. .. change:: :tags: bug Removed unnecessary "usage" prefix from mako-render script. Pull request courtesy Hugo. .. changelog:: :version: 1.0.7 :released: Thu Jul 13 2017 .. change:: :tags: bug Changed the "print" in the mako-render command to sys.stdout.write(), avoiding the extra newline at the end of the template output. Pull request courtesy Yves Chevallier. .. changelog:: :version: 1.0.6 :released: Wed Nov 9 2016 .. change:: :tags: feature Added new parameter :paramref:`.Template.include_error_handler` . This works like :paramref:`.Template.error_handler` but indicates the handler should take place when this template is included within another template via the ``<%include>`` tag. Pull request courtesy Huayi Zhang. .. changelog:: :version: 1.0.5 :released: Wed Nov 2 2016 .. change:: :tags: bug Updated the Sphinx documentation builder to work with recent versions of Sphinx. .. changelog:: :version: 1.0.4 :released: Thu Mar 10 2016 .. change:: :tags: feature, test The default test runner is now py.test. Running "python setup.py test" will make use of py.test instead of nose. nose still works as a test runner as well, however. .. change:: :tags: bug, lexer :pullreq: github:19 Major improvements to lexing of intricate Python sections which may contain complex backslash sequences, as well as support for the bitwise operator (e.g. pipe symbol) inside of expression sections distinct from the Mako "filter" operator, provided the operator is enclosed within parentheses or brackets. Pull request courtesy Daniel Martin. .. change:: :tags: feature Added new method :meth:`.Template.list_defs`. Pull request courtesy Jonathan Vanasco. .. changelog:: :version: 1.0.3 :released: Tue Oct 27 2015 .. change:: :tags: bug, babel 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 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 Added support for Lingua, a translation extraction system as an alternative to Babel. Pull request courtesy Wichert Akkerman. .. change:: :tags: bug, py3k 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 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 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 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 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 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 occurred 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.3.2/doc/build/conf.py0000644000175000017500000002254314556174701014703 0ustar piotrpiotr# # 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 os import sys # 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(".")) if True: import mako # noqa # -- 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", "changelog", "sphinx_paramlinks", "zzzeeksphinx", ] changelog_render_ticket = "https://github.com/sqlalchemy/mako/issues/%s" changelog_render_pullreq = { "default": "https://github.com/sqlalchemy/mako/pull/%s", "github": "https://github.com/sqlalchemy/mako/pull/%s", } # tags to sort on inside of sections changelog_sections = [ "changed", "feature", "bug", "usecase", "moved", "removed", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["templates"] nitpicky = True site_base = os.environ.get("RTD_SITE_BASE", "http://www.makotemplates.org") site_adapter_template = "docs_adapter.mako" site_adapter_py = "docs_adapter.py" # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "Mako" copyright = "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 = "1.3.2" release_date = "Tue Jan 30 2024" # 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 = "zsmako" # 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 html_copy_source = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True html_show_sourcelink = False # 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(".", "_"), "Mako Documentation", "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 = r"\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", "Mako Documentation", ["Mako authors"], 1)] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = "Mako" epub_author = "Mako authors" epub_publisher = "Mako authors" epub_copyright = "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 mako-1.3.2/doc/build/defs.rst0000644000175000017500000004245414556174701015062 0ustar piotrpiotr.. _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.3.2/doc/build/filtering.rst0000644000175000017500000002601614556174701016120 0ustar piotrpiotr.. _filtering_toplevel: ======================= Filtering and Buffering ======================= .. _expression_filtering: 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`` * ``str`` : produces a Python unicode string (this function is applied by default) * ``unicode`` : aliased to ``str`` above .. versionchanged:: 1.2.0 Prior versions applied the ``unicode`` built-in when running in Python 2; in 1.2.0 Mako applies the Python 3 ``str`` built-in. * ``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 ``["str"]``: .. sourcecode:: python t = TemplateLookup(directories=['/tmp'], default_filters=['str']) To replace the usual ``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=['str', '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=['str', '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(str("some text"))) .. _expression_filtering_nfilter: 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. Including the ``n`` filter in a ``<%page>`` tag will only disable ``default_filters``. In effect this makes the filters from the tag replace default filters instead of adding to them. For example: .. sourcecode:: mako <%page expression_filter="n, json.dumps"/> data = {a: ${123}, b: ${"123"}}; will suppress turning the values into strings using the default filter, so that ``json.dumps`` (which requires ``imports=["import json"]`` or something equivalent) can take the value type into account, formatting numbers as numeric literals and strings as string literals. .. versionadded:: 1.0.14 The ``n`` filter can now be used in the ``<%page>`` tag. 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.3.2/doc/build/index.rst0000644000175000017500000000041414556174701015236 0ustar piotrpiotrTable of Contents ================= .. toctree:: :maxdepth: 2 usage syntax defs runtime namespaces inheritance filtering unicode caching changelog Indices and Tables ------------------ * :ref:`genindex` * :ref:`search` mako-1.3.2/doc/build/inheritance.rst0000644000175000017500000004644014556174701016431 0ustar piotrpiotr.. _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.3.2/doc/build/namespaces.rst0000644000175000017500000003435714556174701016263 0ustar piotrpiotr.. _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 responsible 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.3.2/doc/build/requirements.txt0000644000175000017500000000033114556174701016657 0ustar piotrpiotrgit+https://github.com/sqlalchemyorg/changelog.git#egg=changelog git+https://github.com/sqlalchemyorg/sphinx-paramlinks.git#egg=sphinx-paramlinks git+https://github.com/sqlalchemyorg/zzzeeksphinx.git#egg=zzzeeksphinx mako-1.3.2/doc/build/runtime.rst0000644000175000017500000003741114556174701015621 0ustar piotrpiotr.. _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.3.2/doc/build/syntax.rst0000644000175000017500000003342714556174701015467 0ustar piotrpiotr.. _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``, ``with``, 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. Further details on what ``<%page>`` is used for are described in the following sections: * :ref:`namespaces_body` - ``<%page>`` is used to define template-level arguments and defaults * :ref:`expression_filtering` - expression filters can be applied to all expressions throughout a template using the ``<%page>`` tag * :ref:`caching_toplevel` - options to control template-level caching may be applied in the ``<%page>`` tag. ``<%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.3.2/doc/build/unicode.rst0000644000175000017500000001241714556174701015563 0ustar piotrpiotr.. _unicode_toplevel: =================== The Unicode Chapter =================== In normal Mako operation, all parsed template constructs and output streams are handled internally as Python 3 ``str`` (Unicode) objects. It's only at the point of :meth:`~.Template.render` that this stream of Unicode objects 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, although Mako defaults to ``utf-8``), 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 ========================================== .. versionchanged:: 1.1.3 As of Mako 1.1.3, the default template encoding is "utf-8". Previously, a Python "magic encoding comment" was required for templates that were not using ASCII. Mako templates support Python's "magic encoding comment" syntax described in `pep-0263 `_: .. 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! » 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(str("hello world")) That is, **the output of all expressions is run through the ``str`` built-in**. This is the default setting, and can be modified to expect various encodings. The ``str`` 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**. 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 ``str`` 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 ``str`` function, since unlike ``str`` 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 ``str`` object: .. 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')) mako-1.3.2/doc/build/unreleased/0000755000175000017500000000000014556174701015525 5ustar piotrpiotrmako-1.3.2/doc/build/unreleased/README.txt0000644000175000017500000000060114556174701017220 0ustar piotrpiotrindividual per-changelog files go here in .rst format, which are pulled in by changelog to be rendered into the changelog.rst file. At release time, the files here are removed and written directly into the changelog. Rationale is so that multiple changes being merged into gerrit don't produce conflicts. Note that gerrit does not support custom merge handlers unlike git itself. mako-1.3.2/doc/build/usage.rst0000644000175000017500000004265414556174701015247 0ustar piotrpiotr.. _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 io 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.3.2/examples/0000755000175000017500000000000014556174701013350 5ustar piotrpiotrmako-1.3.2/examples/bench/0000755000175000017500000000000014556174701014427 5ustar piotrpiotrmako-1.3.2/examples/bench/basic.py0000644000175000017500000001470114556174701016065 0ustar piotrpiotr# 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 io import StringIO import sys import timeit __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)] 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 lookup = TemplateLookup(directories=[dirname], filesystem_checks=False) template = lookup.get_template("template.html") def render(): return template.render(title=TITLE, user=USER, list_items=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=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": 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.3.2/examples/bench/cheetah/0000755000175000017500000000000014556174701016030 5ustar piotrpiotrmako-1.3.2/examples/bench/cheetah/footer.tmpl0000644000175000017500000000003114556174701020216 0ustar piotrpiotr mako-1.3.2/examples/bench/cheetah/header.tmpl0000644000175000017500000000005514556174701020156 0ustar piotrpiotr mako-1.3.2/examples/bench/cheetah/template.tmpl0000644000175000017500000000124614556174701020544 0ustar piotrpiotr ${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.3.2/examples/bench/django/0000755000175000017500000000000014556174701015671 5ustar piotrpiotrmako-1.3.2/examples/bench/django/templates/0000755000175000017500000000000014556174701017667 5ustar piotrpiotrmako-1.3.2/examples/bench/django/templates/base.html0000644000175000017500000000051714556174701021472 0ustar piotrpiotr {% block body %} {{ block.super }} {% endblock %} mako-1.3.2/examples/bench/django/templates/template.html0000644000175000017500000000063214556174701022371 0ustar piotrpiotr{% extends "base.html" %} {% load bench %} ${title|escape} {% block body %}
{% greeting user %}
{% greeting "me" %}
{% greeting "world" %}

Loop

{% if items %}
    {% for item in items %} {{ item }} {% endfor %}
{% endif %} {% endblock %} mako-1.3.2/examples/bench/django/templatetags/0000755000175000017500000000000014556174701020363 5ustar piotrpiotrmako-1.3.2/examples/bench/django/templatetags/__init__.py0000644000175000017500000000000014556174701022462 0ustar piotrpiotrmako-1.3.2/examples/bench/django/templatetags/bench.py0000644000175000017500000000030714556174701022014 0ustar piotrpiotrfrom django.template import Library from django.utils.html import escape register = Library() def greeting(name): return "Hello, %s!" % escape(name) greeting = register.simple_tag(greeting) mako-1.3.2/examples/bench/genshi/0000755000175000017500000000000014556174701015704 5ustar piotrpiotrmako-1.3.2/examples/bench/genshi/base.html0000644000175000017500000000046614556174701017512 0ustar piotrpiotr

Hello, ${name}!

${select('*')}