### SimpleCacheImpl Example
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/caching.rst
An example implementation of a local dictionary cache plugin for Mako.
```APIDOC
## SimpleCacheImpl
### Description
An example implementation of a local dictionary cache plugin for Mako.
### Class Definition
```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")
```
### Usage Example
Enabling the above plugin in a template would look like:
```python
from mako.template import Template
t = Template("mytemplate",
file="mytemplate.html",
cache_impl='simple')
```
```
--------------------------------
### Basic TemplateLookup Setup
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/usage.rst
Shows the initial setup of TemplateLookup, which is used to resolve template resources, including included files. It requires a list of directories to search for templates.
```python
from mako.template import Template
from mako.lookup import TemplateLookup
mylookup = TemplateLookup(directories=['/docs'])
mytemplate = Template("%3C%25include file=\"header.txt\"/%3E hello world!", lookup=mylookup)
```
--------------------------------
### Python SimpleCacheImpl for Mako
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/caching.rst
An example of a custom cache implementation using a local dictionary. It extends Mako's CacheImpl and provides methods for getting, setting, and invalidating cache entries. Register this plugin using register_plugin.
```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")
```
--------------------------------
### Gettext Catalog Example
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/usage.rst
This is an example of a gettext catalog entry generated by Babel. It includes translator comments and message IDs.
```pot
#. TRANSLATORS: This is a proper name. See the gettext
#. manual, section Names.
#: myproj/templates/name.html:5
msgid "Francois Pinard"
msgstr ""
```
--------------------------------
### Basic Mako Template Example
Source: https://github.com/sqlalchemy/mako/blob/main/README.rst
Demonstrates basic Mako template syntax including inheritance, variable assignment, loops, and defining custom functions. Use this for creating dynamic HTML structures.
```python
<%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
%def>
```
--------------------------------
### Mako Caching with Beaker Backend
Source: https://context7.com/sqlalchemy/mako/llms.txt
Demonstrates template caching using the 'beaker' backend with configurable timeouts and programmatic invalidation. Ensure 'beaker' is installed.
```python
from mako.template import Template
import time
# This content is cached for 60 seconds
Generated at: ${time.strftime('%H:%M:%S')}
""", imports=["import time"], cache_impl="beaker",
cache_args={"type": "memory"})
# First render generates and caches
output1 = t.render()
# Second render returns cached value (same timestamp)
output2 = t.render()
assert output1 == output2
# Invalidate the body cache programmatically
t.cache.invalidate_body()
```
```python
# ── Cache individual defs ─────────────────────────────────────────────────────
t2 = Template("""
<%def name="sidebar()" cached="True" cache_timeout="300">
Expensive sidebar content
%def>
<%def name="header()">
Always fresh header
%def>
${header()}
${sidebar()}
""", cache_impl="beaker", cache_args={"type": "memory"})
t2.render()
# Invalidate just the sidebar def
t2.cache.invalidate_def("sidebar")
```
--------------------------------
### Namespace API Usage Example - Static Dependencies (Version Two - Use a specific named def)
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/namespaces.rst
This example shows an alternative method where static dependencies are placed within a named '<%def>' block. The base template then calls this specific def on each namespace to retrieve the necessary includes.
```APIDOC
## 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>
<%def name="mytag()">
%def>
## index.mako
## calling template.
<%inherit file="base.mako"/>
<%namespace name="foo" file="library.mako"/>
<%foo:mytag>
a form
%foo:mytag>
```
--------------------------------
### Define and Render Mako Template with Definitions
Source: https://github.com/sqlalchemy/mako/wiki/imported_issue_attachments/102/functional_def_render.txt
Shows how to define reusable template functions (defs) within a Mako template and then render them with specific arguments. Ensure Mako is installed.
```python
from mako.template import Template
```
```python
template = Template("""
<%def name="hi(name)">
hi ${name}!
%def>
<%def name="bye(name)">
bye ${name}!
%def>
""")
```
```python
print template.get_def("hi").render(name="ed")
```
--------------------------------
### English Translation Example
Source: https://github.com/sqlalchemy/mako/blob/main/test/templates/internationalization.html
This is an example of a .po file entry for an English translation. It shows the original message ID and its corresponding translation.
```ini
#: translate_demo\controllers\hello.py:6 translate_demo\controllers\hello.py:9
msgid "Hello"
msgstr "Hello"
```
--------------------------------
### Mako Template Inheritance Example
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/inheritance.rst
Demonstrates how an inheriting template can override blocks defined in a base template. Use this to extend base layouts with specific content.
```mako
## index.html
<%inherit file="base.html"/>
<%block name="header">
this is some header content
${parent.header()}
%block>
<%block name="title">
this is the title
%block>
this is the body content.
```
--------------------------------
### Jinja2 Macro and Inclusion Example
Source: https://github.com/sqlalchemy/mako/blob/main/examples/bench/jinja2/template.html
Defines a reusable macro for greetings and includes other templates. Useful for creating dynamic HTML content.
```html
{% title %} {%- macro greeting(name) %}
hello {{ name }}
{%- endmacro %} {% include "header.html" %} {{ greeting(user) }} {{ greeting('me') }} {{ greeting('world') }}
```
--------------------------------
### Call Mako Body Method with Arguments
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/namespaces.rst
Provides an example of calling the body() method with specific arguments, including positional and keyword arguments. This is used when the body method's signature has been explicitly defined.
```mako
${self.body(5, y=10, someval=15, delta=7)}
```
--------------------------------
### Spanish Translation Example
Source: https://github.com/sqlalchemy/mako/blob/main/test/templates/internationalization.html
This is an example of a .po file entry for a Spanish translation. It shows the original message ID and its corresponding translation.
```ini
#: translate_demo\controllers\hello.py:6 translate_demo\controllers\hello.py:9
msgid "Hello"
msgstr "°Hola!"
```
--------------------------------
### French Translation Example
Source: https://github.com/sqlalchemy/mako/blob/main/test/templates/internationalization.html
This is an example of a .po file entry for a French translation. It shows the original message ID and its corresponding translation.
```ini
#: translate_demo\controllers\hello.py:6 translate_demo\controllers\hello.py:9
msgid "Hello"
msgstr "Bonjour"
```
--------------------------------
### Namespace API Usage Example - Static Dependencies (Version One - Use :attr:`.Namespace.attr`)
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/namespaces.rst
This example demonstrates how to use the :attr:`.Namespace.attr` attribute to access variables declared in the '<%! %>` section of a template, enabling the base template to dynamically include resources declared in child namespaces.
```APIDOC
## 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()">
%def>
## index.mako
## calling template.
<%inherit file="base.mako"/>
<%namespace name="foo" file="library.mako"/>
<%foo:mytag>
a form
%foo:mytag>
```
--------------------------------
### Example Usage of decode_request
Source: https://github.com/sqlalchemy/mako/blob/main/test/templates/internationalization.html
Demonstrates how to use the `decode_request` function to process request parameters. Avoid using with file uploads.
```python
unicode_params = decode_request(request.params)
```
--------------------------------
### Basic Translation String
Source: https://github.com/sqlalchemy/mako/blob/main/test/templates/internationalization.html
This is an example of a string that would be extracted for translation using a function like _().
```python
msg = _("He told her not to go outside")
```
--------------------------------
### Mako Template with Gettext Message Extraction
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/usage.rst
Example of a Mako template demonstrating the use of the '_()' function for gettext message extraction, including translator comments.
```mako
Name:
## TRANSLATORS: This is a proper name. See the gettext
## manual, section Names.
${_('Francois Pinard')}
```
--------------------------------
### Define and Call Macro with Unicode Argument
Source: https://github.com/sqlalchemy/mako/blob/main/test/templates/unicode_arguments_py3k.html
Defines a Mako macro 'my_def' that accepts an argument 'x' and renders it. The example shows calling this macro with a Unicode string literal.
```html
<%def name="my_def(x)">
x is: ${x}
%def>
${my_def('drôle de petite voix m’a réveillé')}
```
--------------------------------
### Apply Multiple Filters (HTML Escape and Trim)
Source: https://github.com/sqlalchemy/mako/blob/main/doc/build/filtering.rst
Combine multiple filters by separating them with commas. The filters are applied in order from left to right. This example applies HTML escaping first, then trims whitespace.
```mako
${ " some value " | h,trim }
```
--------------------------------
### Include Translation Catalogs in setup.py
Source: https://github.com/sqlalchemy/mako/blob/main/test/templates/internationalization.html
Configure your setup.py file to include the necessary translation catalog files (.mo) within the distributed egg.
```python
package_data={'translate_demo': ['i18n/*/LC_MESSAGES/*.mo']},
```
--------------------------------
### Template Class Initialization and Rendering
Source: https://context7.com/sqlalchemy/mako/llms.txt
Demonstrates how to create a `Template` object from a string or file and render its content. It also shows options for handling undefined variables and custom default filters.
```APIDOC
## Template
Compile and render a template from text or file
`Template` is the primary class for compiling a Mako template and rendering it into a string. It accepts either a `text` string or a `filename` path as the template source, along with numerous configuration options for encoding, filtering, caching, and error handling.
### Usage
```python
from mako.template import Template
# Render from a string
t = Template("""
Hello, ${name}!
Your items:
% for item in items:
- ${item | h}
% endfor
""")
result = t.render(name="Alice", items=["