### Mako Template Inheritance Example Source: https://docs.makotemplates.org/en/latest/inheritance.html Demonstrates basic template inheritance using 'inherit' and 'block' tags. The inheriting template 'index.html' extends 'base.html'. ```html ## index.html <%inherit file="base.html"/> <%block name="header"> this is some header content this is the body content. ``` ```html ## base.html
<%block name="header"/>
${self.body()} ``` -------------------------------- ### Basic Decorator Example Source: https://docs.makotemplates.org/en/latest/filtering.html Illustrates a simple decorator function 'bar' that wraps a 'foo' def, adding 'BAR' output before and after the original content. The decorator writes directly to the context. ```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()} ``` -------------------------------- ### Implement a Simple Dictionary Cache Plugin Source: https://docs.makotemplates.org/en/latest/caching.html Example of a custom CacheImpl subclass that uses a local dictionary for caching. It implements methods for getting or creating, setting, getting, and invalidating cache entries. The plugin can be registered locally 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") ``` -------------------------------- ### Context Methods Source: https://docs.makotemplates.org/en/latest/runtime.html Provides runtime namespace, output buffer, and callstacks for templates. Includes methods for getting values, managing keys, handling callers, and writing to the output buffer. ```APIDOC ## mako.runtime.Context ### Description Provides runtime namespace, output buffer, and various callstacks for templates. ### Methods - **get(_key_, _default_ =None_)**: Return a value from this `Context`. - **keys()**: Return a list of all names established in this `Context`. - **pop_caller()**: Pop a `caller` callable onto the callstack for this `Context`. - **push_caller(_caller_)**: Push a `caller` callable onto the callstack for this `Context`. - **write(_string_)**: Write a string to this `Context` object’s underlying output buffer. - **writer()**: Return the current writer function. ### Properties - **kwargs**: Return the dictionary of top level keyword arguments associated with this `Context`. - **lookup**: Return the `TemplateLookup` associated with this `Context`. ``` -------------------------------- ### Mako runner script usage Source: https://docs.makotemplates.org/en/latest/changelog.html Example of using the 'mako-render' script to render standard input as a template to standard output. This script is useful for command-line template processing. ```bash mako-render ``` -------------------------------- ### Babel Command Line Extraction Source: https://docs.makotemplates.org/en/latest/usage.html Example of invoking Babel's extract command to generate a gettext catalog from Mako templates using a specified configuration file and comment prefix. ```bash myproj$ pybabel extract -F babel.cfg -c "TRANSLATORS:" . ``` -------------------------------- ### Calling a Def with Embedded Content Source: https://docs.makotemplates.org/en/latest/defs.html This example shows how to call a def that expects embedded content, similar to how you might use a template tag with a body. ```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
``` -------------------------------- ### Incorrect Use of <%include%> with Template Inheritance Source: https://docs.makotemplates.org/en/latest/inheritance.html This example shows a common mistake where <%include%> is used with template inheritance, leading to blocks in the included file not being overridden by the child template. ```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 ``` -------------------------------- ### Custom Module Writer Function Source: https://docs.makotemplates.org/en/latest/usage.html Example of a custom module writer function that mimics the default atomic behavior using tempfile and shutil.move. This is useful for advanced module writing overrides. ```python import tempfile import os import shutil def module_writer(source, outputpath): (dest, name) = tempfile.mkstemp( dir=os.path.dirname(outputpath) ) os.write(dest, source) os.close(dest) shutil.move(name, outputpath) from mako.template import Template mytemplate = Template( filename="index.html", module_directory="/path/to/modules", module_writer=module_writer ) ``` -------------------------------- ### Mako 'bytestring passthru' mode example Source: https://docs.makotemplates.org/en/latest/changelog.html Illustrates enabling 'bytestring passthru' mode by passing disable_unicode=True to Template or TemplateLookup. This mode disables unicode awareness for potential speed improvements. ```python Template(..., disable_unicode=True) ``` ```python TemplateLookup(..., disable_unicode=True) ``` -------------------------------- ### Configure Output Encoding and Error Handling Source: https://docs.makotemplates.org/en/latest/unicode.html Set the desired output encoding and error handling strategy for rendered templates using `output_encoding` and `encoding_errors` parameters in TemplateLookup. This example uses 'utf-8' and 'replace' for errors. ```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()) ``` -------------------------------- ### Define a Simple 'hello' Def Source: https://docs.makotemplates.org/en/latest/defs.html Defines a basic Mako def named 'hello' that outputs the string 'hello world'. This def requires a 'name' attribute referencing a Python function signature. ```html <%def name="hello()"> hello world ``` -------------------------------- ### Create and Render a Basic Mako Template Source: https://docs.makotemplates.org/en/latest/usage.html Demonstrates the simplest way to create a Mako template from a string and render its output. The template text is compiled into a Python module with a render_body() function. ```python from mako.template import Template mytemplate = Template("hello world!") print(mytemplate.render()) ``` -------------------------------- ### Escape the Percent Sign Source: https://docs.makotemplates.org/en/latest/syntax.html To output a literal percent sign as the first non-whitespace character on a line, escape it using '%%'. This applies to both the start of a line and indented lines. ```mako %% some text %% some more text ``` -------------------------------- ### Dynamic Namespace File Path Source: https://docs.makotemplates.org/en/latest/namespaces.html Demonstrates how to use an expression for the 'file' argument in <%namespace%>, allowing dynamic resolution of the namespace file path based on context variables. ```html <%namespace name="dyn" file="${context['namespace_name']}"/> ``` -------------------------------- ### Scenario with Multiple Block Renders Using Namespace Source: https://docs.makotemplates.org/en/latest/inheritance.html Illustrates a scenario where both base and child blocks are rendered by using <%namespace%> to call upon blocks from an included child template. ```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 ``` -------------------------------- ### Index Template Inheriting from Layout Source: https://docs.makotemplates.org/en/latest/inheritance.html The index template inherits from the intermediate layout template. It represents the bottom of the inheritance chain for this example, providing the main body content. ```html <%inherit file="layout.html"/> ## .. rest of template ``` -------------------------------- ### Correct Use of <%namespace%> for Includes with Inheritance Source: https://docs.makotemplates.org/en/latest/inheritance.html Demonstrates the correct way to include templates with inheritance by using <%namespace%> to access blocks from the included file, allowing them to be overridden. ```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 ``` -------------------------------- ### Simulating Blocks with Defs Source: https://docs.makotemplates.org/en/latest/inheritance.html Demonstrates how to achieve a similar effect to `<%block>` using `<%def>` by placing the definition and invocation together. This approach is less streamlined than using `<%block>`. ```html
<%def name="header()">this is some header content${self.header()}
``` -------------------------------- ### Propagate Context Variables as Keyword Arguments Source: https://docs.makotemplates.org/en/latest/runtime.html Use the `kwargs` accessor to get a copy of the context's variables. This is useful for passing context variables as keyword arguments to functions. ```python ${next.body(**context.kwargs)} ``` -------------------------------- ### Import and Use Namespace Definitions Source: https://docs.makotemplates.org/en/latest/namespaces.html Imports definitions from 'components.html' into a namespace named 'comp' and then calls them. ```html <%namespace name="comp" file="components.html"/> Here's comp1: ${comp.comp1()} Here's comp2: ${comp.comp2(x=5)} ``` -------------------------------- ### Initialize TemplateLookup from Directories Source: https://docs.makotemplates.org/en/latest/usage.html Instantiate TemplateLookup with a list of directories to search for templates. Then, retrieve a template using its URI. ```python lookup = TemplateLookup(["/path/to/templates"]) some_template = lookup.get_template("/index.html") ``` -------------------------------- ### Get Template using TemplateLookup Source: https://docs.makotemplates.org/en/latest/usage.html Retrieve a template by its URI using TemplateLookup, which handles searching in configured directories and caching. This method is typically used in applications to serve templates dynamically. ```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)) ``` -------------------------------- ### Import All Definitions from Namespace Source: https://docs.makotemplates.org/en/latest/namespaces.html Imports all definitions from 'components.html' into the current namespace using the wildcard '*'. This allows direct calls to all imported definitions. ```html <%namespace file="components.html" import="*"/> Heres comp1: ${comp1()} Heres comp2: ${comp2(x=5)} ``` -------------------------------- ### TemplateLookup Initialization and Usage Source: https://docs.makotemplates.org/en/latest/usage.html Demonstrates how to initialize a TemplateLookup object to search for templates in specified directories and retrieve a template. ```APIDOC ## TemplateLookup Class ### Description Represents a collection of templates that locates template source files from the local filesystem. ### Parameters * **directories** (list) - A list of directory names which will be searched for a particular template URI. * **collection_size** (int) - Approximate size of the collection used to store templates. Defaults to -1 (unbounded). * **filesystem_checks** (bool) - When True, compares filesystem last modified time to regenerate templates. Defaults to True. * **modulename_callable** (callable) - A callable to determine the generated Python module file path. ### Example Usage ```python lookup = TemplateLookup(["/path/to/templates"]) some_template = lookup.get_template("/index.html") ``` ``` -------------------------------- ### Calling the body() Method with Arguments Source: https://docs.makotemplates.org/en/latest/namespaces.html Illustrates how to invoke the `body()` method of a namespace, passing explicit positional and keyword arguments to it. ```html ${self.body(5, y=10, someval=15, delta=7)} ``` -------------------------------- ### Render Template Output as Unicode String Source: https://docs.makotemplates.org/en/latest/unicode.html Use the `render_unicode()` method to explicitly get the template output as a Python `str` object, regardless of any `output_encoding` settings. This allows for manual encoding if needed. ```python print(mytemplate.render_unicode()) ``` -------------------------------- ### Basic Mako Tag Syntax Source: https://docs.makotemplates.org/en/latest/syntax.html Demonstrates the basic syntax for Mako tags, including self-closing and explicit closing tags. ```html <%include file="foo.txt"/> <%def name="foo" buffered="True"> this is a def ``` -------------------------------- ### Decode Non-ASCII Byte Strings in Expressions Source: https://docs.makotemplates.org/en/latest/unicode.html When an expression returns a byte string containing non-ASCII characters, it must be explicitly decoded to a Python Unicode object before being used. This example shows decoding using UTF-8. ```python ${call_my_object().decode('utf-8')} ``` -------------------------------- ### Def Nesting Limitations in Mako Source: https://docs.makotemplates.org/en/latest/inheritance.html Shows an example where nested `<%def>` tags do not work as expected because inner defs are not part of the template's exported namespace. The inner def must be defined at the top level to be accessible. ```html <%def name="header()"> ## this won't work ! <%def name="title()">default title</%def>${self.title()} ${self.header()} ``` ```html <%def name="header()"> ${self.title()} ${self.header()} <%def name="title()"/> ``` -------------------------------- ### Defining Namespace Arguments with <%page> Source: https://docs.makotemplates.org/en/latest/namespaces.html Shows how to explicitly define the argument signature for a namespace's `body()` method using the `<%page>` tag, including positional, default, and arbitrary keyword arguments. ```html <%page args="x, y, someval=8, scope='foo', **kwargs"/> ``` -------------------------------- ### Def with Arguments and Default Values Source: https://docs.makotemplates.org/en/latest/defs.html Shows how to define a Mako def that accepts arguments, including one with a default value ('type'). This allows for parameterized reusable content. ```html ${account(accountname='john')} <%def name="account(accountname, type='regular')"> account name: ${accountname}, type: ${type} ``` -------------------------------- ### Getting a Namespace by URI Source: https://docs.makotemplates.org/en/latest/namespaces.html Use the get_namespace() method to retrieve a Namespace object corresponding to a given URI. Relative URIs are adjusted based on the current namespace's URI. This is useful for dynamically loading namespaces within template code. ```python get_namespace(_uri_) ``` -------------------------------- ### Define Components in a Namespace File Source: https://docs.makotemplates.org/en/latest/namespaces.html Defines two reusable components, comp1 and comp2, within a Mako template file. ```html <%def name="comp1()"> this is comp1 <%def name="comp2(x)"> this is comp2, x is ${x} ``` -------------------------------- ### Import and Call Def from Another File Source: https://docs.makotemplates.org/en/latest/defs.html Demonstrates how to import a Mako namespace from another file ('mystuff.html') and then call a def ('somedef') defined within that imported namespace. This enables modularity and code reuse across templates. ```html <%namespace name="mystuff" file="mystuff.html"/> ${mystuff.somedef(x=5,y=7)} ``` -------------------------------- ### Configure Beaker CacheManager with Regions Source: https://docs.makotemplates.org/en/latest/caching.html Set up Beaker cache regions for 'short_term' (memory, 60s expiry) and 'long_term' (Memcached, 300s expiry). This configuration is passed to TemplateLookup. ```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 } ) ``` -------------------------------- ### Load Template from File Source: https://docs.makotemplates.org/en/latest/usage.html Load a Mako template directly from a file using the 'filename' argument. This is useful for simple cases where a single template file is needed. ```python from mako.template import Template mytemplate = Template(filename='/docs/mytmpl.txt') print(mytemplate.render()) ``` -------------------------------- ### Using Defs for Inheritance in Mako Source: https://docs.makotemplates.org/en/latest/inheritance.html Illustrates how to use the `<%def>` tag for defining content that can be overridden in an inherited template. The definition and invocation are in separate places. ```html ## index.html <%inherit file="base.html"/> <%def name="header()"> this is some header content this is the body content. ``` ```html ## base.html
${self.header()}
${self.body()} <%def name="header()"/> <%def name="footer()"> this is the footer ``` -------------------------------- ### Configuring cache_key for Mako template arguments Source: https://docs.makotemplates.org/en/latest/changelog.html Shows how to use the 'cache_key' argument with template expressions for cached definitions. This allows cache keys to be dynamically generated based on function arguments. ```html <%def name="foo(x)" cached="True" cache_key="${x}"/> ``` -------------------------------- ### Include Template with Arguments Source: https://docs.makotemplates.org/en/latest/syntax.html The <%include> tag can pass arguments to the included template. ```html <%include file="toolbar.html" args="current_section='members', username='ed'"/> ``` -------------------------------- ### Basic If/Else Control Structure Source: https://docs.makotemplates.org/en/latest/syntax.html Implement conditional logic using the '%' marker followed by a Python control expression and closed with '% endif'. Indentation is not significant. ```mako % if x==5: this is some output % endif ``` -------------------------------- ### Configure Default Filters and Imports (TemplateLookup) Source: https://docs.makotemplates.org/en/latest/filtering.html Sets default filters and imports a custom filter 'myfilter' from 'mypackage' for use in templates. ```python t = TemplateLookup(directories=['/tmp'], default_filters=['str', 'myfilter'], imports=['from mypackage import myfilter']) ``` -------------------------------- ### Cache.get() Source: https://docs.makotemplates.org/en/latest/caching.html Retrieve a value from the cache using its key. Cache configuration arguments can be passed to set up the backend on the first request. ```APIDOC ## Cache.get() ### Description Retrieve a value from the cache. ### Method GET (conceptual) ### Parameters #### Path Parameters - None #### Query Parameters - **key** (string) - Required - The value's key. - ****kw** (dict) - Optional - Cache configuration arguments. ### Request Example ```python # Assuming 'template' is a compiled Mako template object template.cache.get('my_key', config_arg='value') ``` ### Response #### Success Response (200) - **value** (any) - The cached value associated with the key. #### Response Example ```json { "value": "cached_data" } ``` ``` -------------------------------- ### Cache.starttime Source: https://docs.makotemplates.org/en/latest/caching.html The epochal time value indicating when the owning `Template` was first compiled. This can be used by cache implementations to invalidate older cache entries. ```APIDOC ## Cache.starttime ### Description Epochal time value for when the owning `Template` was first compiled. A cache implementation may wish to invalidate data earlier than this timestamp; this has the effect of the cache for a specific `Template` starting clean any time the `Template` is recompiled, such as when the original template file changed on the filesystem. ### Attribute Type integer (epochal time) ### Example ```python compile_time = template.cache.starttime print(f"Template compiled at: {compile_time}") ``` ``` -------------------------------- ### Disable Default Filters and Apply Specific Filter Locally Source: https://docs.makotemplates.org/en/latest/filtering.html Disables all default filters but still allows a specific filter ('trim') to be applied locally. ```mako ${ 'myexpression' | n,trim } ``` -------------------------------- ### Render Mako Template with Explicit Context Source: https://docs.makotemplates.org/en/latest/usage.html Illustrates rendering a Mako template using an explicitly created Context object. This method provides more control over the rendering environment and output buffer. ```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()) ``` -------------------------------- ### Defining and Calling Defs within a Namespace Source: https://docs.makotemplates.org/en/latest/namespaces.html Demonstrates how to declare a namespace and define a function (def) within it, which can then be called using the namespace's name. ```html ## define a namespace <%namespace name="stuff"> <%def name="comp1()"> comp1 ## then call it ${stuff.comp1()} ``` -------------------------------- ### Import Specific Definitions from Namespace Source: https://docs.makotemplates.org/en/latest/namespaces.html Imports specific definitions (comp1, comp2) directly into the current namespace, allowing direct calls without the namespace prefix. ```html <%namespace file="components.html" import="comp1, comp2"/> Heres comp1: ${comp1()} Heres comp2: ${comp2(x=5)} ``` -------------------------------- ### DefTemplate Methods Source: https://docs.makotemplates.org/en/latest/usage.html Methods available on the DefTemplate object. ```APIDOC ## DefTemplate.get_def(_name_) ### Description Return a def of this template as a `DefTemplate`. ### Method `get_def` ### Parameters #### Path Parameters - **_name_** (string) - Description of the def to retrieve. ``` -------------------------------- ### Decorator with Output Capture Source: https://docs.makotemplates.org/en/latest/filtering.html Shows how to use 'runtime.capture' within a decorator to capture and manipulate the output of the decorated function. This allows the decorator to return a modified string. ```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()} ``` -------------------------------- ### Correctly Calling Child Blocks via Namespace Source: https://docs.makotemplates.org/en/latest/inheritance.html Shows how to correctly call blocks from a child template within a parent template using the <%namespace%> directive, ensuring both blocks are rendered. ```mako ## parent.mako <%inherit file="base.mako" /> <%namespace name="child" file="child.mako" /> <%block name="SectionA"> ${child.SectionA()} ``` -------------------------------- ### Apply Filters to Def Source: https://docs.makotemplates.org/en/latest/filtering.html Use the 'filter' argument on a def to apply a list of filter functions to its output. This also automatically buffers the def. ```html <%def name="foo()" filter="h, trim"> this is bold ``` -------------------------------- ### Context Methods and Accessors Source: https://docs.makotemplates.org/en/latest/runtime.html Reference for the Context object's methods and attributes, which manage template variables and output. ```APIDOC ## Context ### Description The `Context` object is central to template execution, managing variables and output. ### Methods and Accessors - **`Context.get(key, default=None)`** - Description: Retrieves a variable from the context. - Parameters: - `key` (string): The name of the variable to retrieve. - `default` (any, optional): The default value to return if the key is not found. - **`Context.keys()`** - Description: Returns a list of all variable names in the context. - Returns: list[string] - **`Context.kwargs`** - Description: A dictionary containing all keyword arguments passed to the template render function. - Type: dict - **`Context.lookup(key)`** - Description: Looks up a variable in the context, similar to `get` but may have different behavior for undefined values. - Parameters: - `key` (string): The name of the variable to look up. - **`Context.pop_caller()`** - Description: Removes and returns the current caller from the call stack. - Returns: The caller object. - **`Context.push_caller(caller)`** - Description: Pushes a new caller onto the call stack. - Parameters: - `caller` (object): The caller object to push. - **`Context.write(text)`** - Description: Writes text to the current output buffer. - Parameters: - `text` (string): The string to write. - **`Context.writer()`** - Description: Returns a callable writer object that can be used to write to the buffer. - Returns: A writer callable. ``` -------------------------------- ### Mako Template with Gettext Message Source: https://docs.makotemplates.org/en/latest/usage.html A sample Mako template demonstrating the use of the gettext function `_()` for translatable strings and translator comments. ```html+mako
Name: ## TRANSLATORS: This is a proper name. See the gettext ## manual, section Names. ${_('Francois Pinard')}
``` -------------------------------- ### Capture Def Output with capture() Source: https://docs.makotemplates.org/en/latest/filtering.html Use the built-in 'capture' function to buffer the output of a def or callable. Pass the function itself as the first argument, not its result. ```html ${' results ' + capture(somedef) + ' more results '} ``` -------------------------------- ### Load Template from File with Module Caching Source: https://docs.makotemplates.org/en/latest/usage.html Load a Mako template from a file and enable caching of its compiled module to the filesystem. This improves performance by reusing generated Python modules for subsequent template loads. ```python from mako.template import Template mytemplate = Template(filename='/docs/mytmpl.txt', module_directory='/tmp/mako_modules') print(mytemplate.render()) ``` -------------------------------- ### Including a File by URI Source: https://docs.makotemplates.org/en/latest/namespaces.html The include_file() method allows you to include the content of a file specified by its URI within the current template context. Additional keyword arguments can be passed as needed. ```python include_file(_uri_ , _** kwargs_) ``` -------------------------------- ### Rendered Output of Mako Inheritance Source: https://docs.makotemplates.org/en/latest/inheritance.html Shows the final HTML output after rendering the 'index.html' and 'base.html' templates with inheritance. ```html
this is some header content
this is the body content. ``` -------------------------------- ### mako.ext.beaker_cache.BeakerCacheImpl.get_or_create Source: https://docs.makotemplates.org/en/latest/caching.html Retrieves a value from the cache using Beaker, creating it if it doesn't exist. ```APIDOC ## mako.ext.beaker_cache.BeakerCacheImpl.get_or_create ### Description Retrieve a value from the cache, using the given creation function to generate a new value. This function must return a value, either from the cache, or via the given creation function. If the creation function is called, the newly created value should be populated into the cache under the given key before being returned. ### Parameters #### Path Parameters - **key** (any) - Required - the value’s key. - **creation_function** (callable) - Required - function that when called generates a new value. - **kw** (any) - Optional - cache configuration arguments. ``` -------------------------------- ### Apply Multiple Filters (HTML Escape and Trim) Source: https://docs.makotemplates.org/en/latest/filtering.html Applies HTML escaping first, followed by whitespace trimming. This ensures HTML safety and clean output. ```mako ${ " some value " | h,trim } ``` -------------------------------- ### Create Template with TemplateLookup Source: https://docs.makotemplates.org/en/latest/usage.html Create a Mako template that includes other templates, using TemplateLookup to manage the resolution of these included templates. The lookup is configured with directories to search for template files. ```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) ``` -------------------------------- ### Render Mako Template with Variables Source: https://docs.makotemplates.org/en/latest/usage.html Shows how to render a Mako template that includes variables. Variables are passed as keyword arguments to the render() method and are accessible within the template's render_body() function. ```python from mako.template import Template mytemplate = Template("hello, ${name}!") print(mytemplate.render(name="jack")) ``` -------------------------------- ### Include Another Template File Source: https://docs.makotemplates.org/en/latest/syntax.html The <%include> tag inserts the rendered content of another file. ```html <%include file="header.html"/> hello world <%include file="footer.html"/> ``` -------------------------------- ### Initialize Template Context with an Empty Dictionary Source: https://docs.makotemplates.org/en/latest/runtime.html When rendering a template, provide an empty dictionary to the 'attributes' argument of template.render() to initialize a global context for variables. ```python output = template.render(attributes={}) ``` -------------------------------- ### Retrieving a Template by URI Source: https://docs.makotemplates.org/en/latest/namespaces.html Use the get_template() method on a Namespace object to fetch a Template instance from a given URI. The URI resolution is relative to the current Namespace's template URI. ```python get_template(_uri_) ``` -------------------------------- ### Extracting Gettext Messages with Babel Source: https://docs.makotemplates.org/en/latest/usage.html Demonstrates how to configure Babel to extract gettext messages from Mako templates. Ensure translator comments immediately precede the message to be extracted. ```ini # Extraction from Python source files [python: myproj/**.py] # Extraction from Mako templates [mako: myproj/templates/**.html] input_encoding = utf-8 ``` -------------------------------- ### Using Blocks for Inheritance in Mako Source: https://docs.makotemplates.org/en/latest/inheritance.html Illustrates the use of `<%block>` tags for defining content that can be overridden. Blocks are always placed in the `self` namespace, regardless of nesting, lifting restrictions of nested defs. ```html ## base.html <%block name="header"> <%block name="title"/> ``` ```html ## index.html <%inherit file="base.html"/> <%block name="title"> the title <%block name="header"> the header ``` -------------------------------- ### mako.runtime.capture Source: https://docs.makotemplates.org/en/latest/namespaces.html Executes a given template def, capturing its output into a buffer. This is useful for scenarios where you need to capture template output programmatically. ```APIDOC function mako.runtime.capture(_context_ , _callable__ , _* args_, _** kwargs_) Execute the given template def, capturing the output into a buffer. See the example in Namespaces from Regular Python Modules. ``` -------------------------------- ### Cache.get_or_create() Source: https://docs.makotemplates.org/en/latest/caching.html Retrieve a value from the cache. If the value is not found, it is created using the provided creation function and then returned. ```APIDOC ## Cache.get_or_create() ### Description Retrieve a value from the cache, using the given creation function to generate a new value if it does not exist. ### Method GET/CREATE (conceptual) ### Parameters #### Path Parameters - None #### Query Parameters - **key** (string) - Required - The value's key. - **creation_function** (callable) - Required - A function that generates the value if it's not in the cache. - ****kw** (dict) - Optional - Cache configuration arguments. ### Request Example ```python def create_my_data(): # Logic to create the data return "newly_created_data" # Assuming 'template' is a compiled Mako template object value = template.cache.get_or_create('my_key', create_my_data, config_arg='value') ``` ### Response #### Success Response (200) - **value** (any) - The cached value or the newly created value. #### Response Example ```json { "value": "cached_data_or_newly_created_data" } ``` ``` -------------------------------- ### Using Inheritable Namespaces in Mako Source: https://docs.makotemplates.org/en/latest/namespaces.html Demonstrates how to define an inheritable namespace in a base template and access it from an inheriting template using the 'self' namespace. The 'inheritable="True"' attribute makes the 'foo' namespace available globally within the inheritance chain. ```html ## base.html <%namespace name="foo" file="foo.html" inheritable="True"/> ${next.body()} ``` ```html ## somefile.html <%inherit file="base.html"/> ${self.foo.bar()} ``` -------------------------------- ### Base Template with `next.body()` Source: https://docs.makotemplates.org/en/latest/inheritance.html This snippet shows a base template that uses `next.body()` to render the content from the inheriting template. This allows for content wrapping by intermediate templates. ```html
<%block name="header"/>
${next.body()} ``` -------------------------------- ### Import Specific Defs from Namespace Source: https://docs.makotemplates.org/en/latest/defs.html Shows how to import specific defs ('foo', 'bar') from a Mako namespace file ('mystuff.html') into the local scope using the 'import' attribute. This is similar to Python's selective import. ```html <%namespace file="mystuff.html" import="foo, bar"/> ``` -------------------------------- ### Configure Default Filters with Custom Filter (Template) Source: https://docs.makotemplates.org/en/latest/filtering.html Applies 'str' and 'myfilter' as default filters to all expressions in the template. Filters are applied from left to right. ```mako t = Template(templatetext, default_filters=['str', 'myfilter']) ``` -------------------------------- ### Cache.set() Source: https://docs.makotemplates.org/en/latest/caching.html Place a value in the cache using a specified key. Cache configuration arguments can be provided to influence backend behavior. ```APIDOC ## Cache.set() ### Description Place a value in the cache. ### Method POST (conceptual) ### Parameters #### Path Parameters - None #### Query Parameters - **key** (string) - Required - The value's key. - **value** (any) - Required - The value to store in the cache. - ****kw** (dict) - Optional - Cache configuration arguments. ### Request Example ```python # Assuming 'template' is a compiled Mako template object template.cache.set('my_key', 'my_value', config_arg='value') ``` ### Response #### Success Response (200) - Indicates successful placement of the value in the cache. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Nested Loops for Checkered Table Source: https://docs.makotemplates.org/en/latest/runtime.html Illustrates how to use 'loop.parent' to access the context of an outer loop within a nested loop, enabling patterns like checkered tables. ```html % for consonant in 'pbj': % for vowel in 'iou': % endfor % endfor
${consonant + vowel}t
``` -------------------------------- ### Zebra Striping with loop.cycle Source: https://docs.makotemplates.org/en/latest/runtime.html A cleaner approach to zebra striping using the 'loop.cycle' function, which alternates between provided values for each iteration. ```html ``` -------------------------------- ### Enable Custom Cache Plugin in Template Source: https://docs.makotemplates.org/en/latest/caching.html Configure a Mako Template to use a custom cache implementation by specifying the cache_impl argument during Template instantiation. ```python t = Template("mytemplate", file="mytemplate.html", cache_impl='simple') ``` -------------------------------- ### Handle Template Exceptions with HTML Output Source: https://docs.makotemplates.org/en/latest/usage.html Use `exceptions.html_error_template()` to catch and format exceptions into an HTML representation. This is useful for displaying errors in a web context. ```python from mako import exceptions try: template = lookup.get_template(uri) print(template.render()) except: print(exceptions.html_error_template().render()) ``` -------------------------------- ### Define Custom Tag with Namespace Source: https://docs.makotemplates.org/en/latest/syntax.html Use this syntax to create a custom tag within a specific namespace. The closed format acts as an inline expression, while the open format is equivalent to a <%call> tag. ```html <%mynamespace:somedef param="some value"> this is the body ``` -------------------------------- ### Def with Contextual Namespace Access Source: https://docs.makotemplates.org/en/latest/defs.html Illustrates a Mako def that accesses variables ('username', 'accountdata') from the surrounding template's context. This shows that defs share the same namespace as their containing template. ```html 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 ``` -------------------------------- ### Using Python Module in Mako Template Source: https://docs.makotemplates.org/en/latest/namespaces.html Demonstrates how to import a Python module as a namespace and call its functions within a Mako template. ```mako <%namespace name="hw" module="some.module"/> ${hw.my_tag()} ``` -------------------------------- ### mako.cache.CacheImpl.set Source: https://docs.makotemplates.org/en/latest/caching.html Places a value into the cache under a specified key. ```APIDOC ## mako.cache.CacheImpl.set ### Description Place a value in the cache. ### Parameters #### Path Parameters - **key** (any) - Required - the value’s key. - **value** (any) - Required - the value. - **kw** (any) - Optional - cache configuration arguments. ``` -------------------------------- ### Include Static Assets via Namespace Attribute Source: https://docs.makotemplates.org/en/latest/namespaces.html Use this method when static assets are declared as a list within the `<%! %>` block of a template. The parent template iterates through namespaces and accesses the declared attribute to render the includes. ```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 ``` -------------------------------- ### Enable Caching for a Mako Page Source: https://docs.makotemplates.org/en/latest/caching.html Use the `cached="True"` argument on the `<%page>` directive to enable caching for a template. The content will be stored in memory by default and served from the cache on subsequent renders. ```html <%page cached="True"/> template text ```