### Setup.cfg Configuration for Babel Commands Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Provides example configuration in setup.cfg for Babel commands like compile_catalog, extract_messages, init_catalog, and update_catalog. ```xml [compile_catalog] domain = mydomain directory = i18n [extract_messages] copyright_holder = Acme Inc. output_file = i18n/mydomain.pot charset = UTF-8 [init_catalog] domain = mydomain input_file = i18n/mydomain.pot output_dir = i18n [update_catalog] domain = mydomain input_file = i18n/mydomain.pot output_dir = i18n previous = true ``` -------------------------------- ### Zope TAL: Content Example Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Demonstrates how to render content using the 'options' dictionary in Zope's reference implementation. ```xml
``` -------------------------------- ### Install Chameleon Source: https://github.com/malthe/chameleon/blob/master/docs/index.md Install the Chameleon package using pip. ```default $ pip install Chameleon ``` -------------------------------- ### GNU gettext Message Catalog Example Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md An example of a GNU gettext message catalog file (.po format) used for translations. This file maps original message IDs to their translated strings. ```po # ./locales/de/LC_MESSAGES/food.po msgid "" msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" msgid "Apple" msgstr "Apfel" ``` -------------------------------- ### Macro Expansion Language (METAL) Example Source: https://github.com/malthe/chameleon/blob/master/docs/index.md Shows how to use METAL to load and fill slots in a generic template. The 'use-macro' attribute loads a template, and 'metal:fill-slot' defines content for a slot. ```genshi

${structure: document.body}

Example — ${document.title}

${document.title}

``` -------------------------------- ### Python Setup for Message Extraction Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Configures setuptools to use Chameleon extractors for Babel to process Python and template files for internationalization. ```python from setuptools import setup setup(name="mypackage", install_requires = [ "Babel", ], message_extractors = { "src": [ ("**.py", "chameleon_python", None ), ("**.pt", "chameleon_xml", None ), ]}, ) ``` -------------------------------- ### Basic Page Template Example Source: https://github.com/malthe/chameleon/blob/master/docs/index.md Demonstrates basic text insertion and nested repetition using TAL syntax. Use ${...} for text insertion, which escapes the output by default. Use structure: prefix to avoid escaping. ```genshi

Hello, ${'world'}!

${row.capitalize()} ${col}
``` -------------------------------- ### Chameleon TAL: Content Example Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Shows direct access to template arguments in Chameleon, bypassing the 'options' dictionary. ```xml
``` -------------------------------- ### Using Default Namespace Prefixes Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Demonstrates how to use TAL directives without explicit namespace declarations, leveraging Chameleon's default prefix setup for common namespaces. ```xml

...

``` -------------------------------- ### Internationalization (I18N) Example Source: https://github.com/malthe/chameleon/blob/master/docs/index.md Demonstrates how to mark text for translation using i18n attributes. 'i18n:domain' sets the translation domain, and 'i18n:translate' marks translatable content. 'i18n:name' can be used to map variables within the translated string. ```genshi ...
You have ${round(amount, 2)} dollars in your account.
... ``` -------------------------------- ### Basic TALES Expressions Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Examples of basic TALES expressions, including arithmetic, None, and string interpolation. ```plaintext 1 + 2 ``` ```plaintext None ``` ```plaintext string:Hello, ${view.user_name} ``` -------------------------------- ### TAL Statements for Dynamic Content Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Provides an example of using multiple TAL statements (tal:condition, tal:repeat, tal:content) within an HTML structure to dynamically render content based on data. ```xml </meta> <body> <div tal:condition="items"> <p>These are your items:</p> <ul> <li tal:repeat="item items" tal:content="item" /> </ul> </div> </body> </html> ``` -------------------------------- ### Multi-line Python Code Block in Template Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Shows how a Python code block can span multiple lines, starting on the line following the processing instruction. ```html <?python foo = [1, 2, 3] ?> ``` -------------------------------- ### Implement Custom Translation Domain Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md An example of a custom translation domain class that implements the ITranslationDomain interface. This allows integration with other translation catalog implementations. ```python from zope import interface class TranslationDomain(object): interface.implements(ITranslationDomain) def translate(self, msgid, mapping=None, context=None, target_language=None, default=None): ... component.provideUtility(TranslationDomain(), name="custom") ``` -------------------------------- ### Direct Babel Command Execution Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Shows how to execute Babel commands directly using python setup.py for message extraction, catalog updates, and compilation. ```xml python setup.py extract_messages python setup.py update_catalog python setup.py compile_catalog ``` -------------------------------- ### Babel Commands for Message Extraction and Catalog Management Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Illustrates the command-line usage of Babel via setup.py for extracting messages and updating/compiling translation catalogs. ```bash python setup.py extract_messages --output-file=i18n/mydomain.pot python setup.py update_catalog \ -l nl \ -i i18n/mydomain.pot \ -o i18n/nl/LC_MESSAGES/mydomain.po python setup.py compile_catalog \ --directory i18n --locale nl ``` -------------------------------- ### Generated gettext String Source: https://github.com/malthe/chameleon/blob/master/docs/index.md Example of a gettext translation string generated by the I18N system from the i18n markup. ```default "You have ${amount} dollars in your account." ``` -------------------------------- ### PageTemplate Usage Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Illustrates how to create and use PageTemplate instances directly from string input, and how to render them by passing variables as keyword arguments. ```APIDOC ## PageTemplate ### Description Defines a template from a string input and renders it. ### Method `chameleon.PageTemplate(template_string, **config)` ### Parameters #### Path Parameters - **template_string** (string) - Required - The template source code. - **config** - Additional keyword arguments passed to the template constructor. ### Request Example ```python from chameleon import PageTemplate template = PageTemplate("<div>Hello, ${name}.</div>") output = template(name='John') # output will be '<div>Hello, John.</div>' ``` ``` -------------------------------- ### Instantiate PageTemplateLoader with Search Path Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Initialize PageTemplateLoader with a search path, which can be a single string or a list of strings. ```python templates = PageTemplateLoader(path) ``` -------------------------------- ### Configuring Chameleon with Environment Variables Source: https://context7.com/malthe/chameleon/llms.txt Shows how to set environment variables before importing Chameleon to control global behavior like caching, auto-reloading, and debug mode. ```python import os os.environ["CHAMELEON_CACHE"] = "/tmp/chameleon_cache" os.environ["CHAMELEON_RELOAD"] = "true" os.environ["CHAMELEON_DEBUG"] = "true" os.environ["CHAMELEON_EAGER"] = "true" import chameleon from chameleon import PageTemplateFile tmpl = PageTemplateFile("/srv/app/templates/page.pt") if hasattr(tmpl, "source") and tmpl.source: print("Generated source snippet:", tmpl.source[:200]) tmpl2 = PageTemplateFile("/srv/app/templates/page.pt", auto_reload=True, debug=True) ``` -------------------------------- ### PageTemplateLoader Usage Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Demonstrates how to initialize and use the PageTemplateLoader to load templates from a specified path. It shows how to load a template by its name and how to specify a default file extension. ```APIDOC ## PageTemplateLoader ### Description Loads templates from `search_path` (must be a string or a list of strings). ### Method `chameleon.PageTemplateLoader(search_path=None, default_extension=None, **config)` ### Parameters #### Path Parameters - **search_path** (string or list of strings) - Required - The path(s) to search for templates. - **default_extension** (string) - Optional - The default extension to append to template names if they don't have one. - **config** - Additional keyword arguments passed to the template constructor. ### Request Example ```python from chameleon import PageTemplateLoader # Load templates from a specific path templates = PageTemplateLoader(path) example = templates['example.pt'] # Load templates with a default extension templates = PageTemplateLoader(path, ".pt") example = templates['example'] # Pass additional configuration to template constructor templates = PageTemplateLoader(path, debug=True, encoding="utf-8") ``` ``` -------------------------------- ### Omit Tag with tal:omit-tag Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Use `tal:omit-tag` to remove the start and end tags of an element while preserving its content. This is useful for structuring output without adding unnecessary HTML elements. ```xml tal:omit-tag ``` -------------------------------- ### TAL Omit-Tag for Conditional Tag Stripping Source: https://context7.com/malthe/chameleon/llms.txt Use tal:omit-tag to remove an element's start and end tags. It accepts an optional condition; if falsy, tags are kept; if truthy (or omitted), tags are stripped. ```python from chameleon import PageTemplate # Unconditional tag removal — useful for logical grouping without markup tmpl = PageTemplate(""" <ul> <tal:block tal:repeat="section sections" tal:omit-tag=""> <li class="header" tal:content="section['title']">title</li> <li tal:repeat="item section['items']" tal:content="item">item</li> </tal:block> </ul> """) print(tmpl(sections=[ {"title": "Fruits", "items": ["Apple", "Banana"]}, {"title": "Vegs", "items": ["Carrot"]}, ])) # <ul> # <li class="header">Fruits</li> # <li>Apple</li> # <li>Banana</li> # <li class="header">Vegs</li> # <li>Carrot</li> # </ul> # Conditional tag stripping tmpl2 = PageTemplate(""" <b tal:omit-tag="not:bold">I may or may not be bold.</b> """) print(tmpl2(bold=True)) # <b>I may or may not be bold.</b> print(tmpl2(bold=False)) # I may or may not be bold. ``` -------------------------------- ### Instantiate PageTemplate with String Input Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Directly create a PageTemplate instance from a string containing the template markup. ```python from chameleon import PageTemplate template = PageTemplate("<div>Hello, ${name}.</div>") ``` -------------------------------- ### Iteration with tal:repeat and Metadata Source: https://context7.com/malthe/chameleon/llms.txt Demonstrates basic iteration over a data sequence using `tal:repeat`. It also shows how to access loop metadata like `repeat.row.parity` and `repeat.row.number` for dynamic styling and numbering. ```python from chameleon import PageTemplate # Basic iteration with repeat metadata tmpl = PageTemplate(""" <table> <tr tal:repeat="row data" tal:attributes="class repeat.row.parity"> <td tal:content="repeat.row.number">1</td> <td tal:content="row['name']">Name</td> <td tal:content="row['score']">0</td> <td tal:condition="repeat.row.end">LAST</td> </tr> </table> """) print(tmpl(data=[ {"name": "Alice", "score": 95}, {"name": "Bob", "score": 87}, {"name": "Carol", "score": 91}, ])) # <table> # <tr class="odd"> # <td>1</td><td>Alice</td><td>95</td> # </tr> # <tr class="even"> # <td>2</td><td>Bob</td><td>87</td> # </tr> # <tr class="odd"> # <td>3</td><td>Carol</td><td>91</td><td>LAST</td> # </tr> # </table> ``` -------------------------------- ### Content Substitution with tal:content and tal:replace Source: https://context7.com/malthe/chameleon/llms.txt Explains the difference between `tal:content` (replaces children) and `tal:replace` (replaces the entire element). It also shows how to use the `structure` prefix for inserting raw HTML and string interpolation. ```python from chameleon import PageTemplate tmpl = PageTemplate(""" <article> <h1 tal:content="title">Default Title</h1> <span tal:replace="author">Author</span> <div tal:content="structure body_html"> <p>Placeholder body</p> </div> <footer tal:content="string:Published on ${date}">date</footer> </article> """) print(tmpl( title="Chameleon Guide", author="Alice <alice@example.com>", body_html="<p>First paragraph.</p><p>Second paragraph.</p>", date="2024-12-31" )) # <article> # <h1>Chameleon Guide</h1> # Alice <alice@example.com> # <div><p>First paragraph.</p><p>Second paragraph.</p></div> # <footer>Published on 2024-12-31</footer> # </article> ``` -------------------------------- ### Load Templates with PageTemplateLoader Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Use PageTemplateLoader to set up a directory for templates. It requires an absolute path to the templates directory. ```python import os path = os.path.dirname(__file__) from chameleon import PageTemplateLoader templates = PageTemplateLoader(os.path.join(path, "templates")) ``` -------------------------------- ### Configure SimpleTranslationDomain Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Manually set up and configure a translation domain with messages provided directly. This is useful for simple, direct message mappings. ```python from zope import component from zope.i18n.simpletranslationdomain import SimpleTranslationDomain food = SimpleTranslationDomain("food", { ('de', u'Apple'): u'Apfel', }) component.provideUtility(food, food.domain) ``` -------------------------------- ### Simple Macro Definition Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Defines a macro named 'copyright' with associated content. This demonstrates the basic syntax for defining a macro. ```xml <p metal:define-macro="copyright"> Copyright 2011, <em>Foobar</em> Inc. </p> ``` -------------------------------- ### Import Expression Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Imports module globals into the template namespace. ```xml <div tal:define="compile import: re.compile"> ... </div> ``` -------------------------------- ### Render a Template Instance Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Template instances are callable and accept variables as keyword arguments for rendering. ```python template(name='John') ``` -------------------------------- ### Nested Repeats with tal:repeat Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Demonstrates nested loops using tal:repeat to generate a grid. Defines variables within the loop for calculations. ```xml <table border="1"> <tr tal:repeat="row range(10)"> <td tal:repeat="column range(10)"> <span tal:define="x repeat.row.number; y repeat.column.number; z x * y" tal:replace="string:$x * $y = $z">1 * 1 = 1</span> </td> </tr> </table> ``` -------------------------------- ### Pass Configuration to Template Constructor Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Provide additional keyword arguments to PageTemplateLoader, which will be passed to the template constructor for each loaded template. ```python templates = PageTemplateLoader(path, debug=True, encoding="utf-8") ``` -------------------------------- ### Switch and Case Statements Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Introduces tal:switch and tal:case attributes for conditional content rendering based on matching values. ```xml <div tal:switch="condition"> <span tal:case="value1">Content for value1</span> <span tal:case="value2">Content for value2</span> </div> ``` -------------------------------- ### PageTemplate - String-based XML/HTML template Source: https://context7.com/malthe/chameleon/llms.txt Creates a template from a string. The template is compiled immediately on construction. Instances are callable; all keyword arguments become template variables. Supports all TAL, METAL, and I18N attributes plus inline ${...} expression substitution. ```APIDOC ## PageTemplate ### Description Creates a template from a string. The template is compiled immediately on construction. Instances are callable; all keyword arguments become template variables. Supports all TAL, METAL, and I18N attributes plus inline `${...}` expression substitution. ### Usage ```python from chameleon import PageTemplate # Basic variable substitution with auto-escaping tmpl = PageTemplate("<p>Hello, ${name}!</p>") print(tmpl(name="Alice")) # <p>Hello, Alice!</p> # Inline expressions in attribute values tmpl2 = PageTemplate( '<a href="/user/${user_id}" class="${\"active\" if active else \"\"}">Profile</a>' ) print(tmpl2(user_id=42, active=True)) # <a href="/user/42" class="active">Profile</a> # Raw/unescaped HTML with structure: prefix html_body = "<strong>Bold content</strong>" tmpl3 = PageTemplate("<div>${structure: body}</div>") print(tmpl3(body=html_body)) # <div><strong>Bold content</strong></div> # Rendering via .render() is identical to calling the instance result = tmpl.render(name="Bob") print(result) # <p>Hello, Bob!</p> # Custom translation hook passed at render time def my_translate(msgid, domain=None, mapping=None, context=None, target_language=None, default=None): catalog = {"Hello": "Hola"} return catalog.get(msgid, default or msgid) tmpl4 = PageTemplate('<p i18n:translate="">Hello</p>') print(tmpl4(translate=my_translate, target_language="es")) # <p>Hola</p> # Boolean attributes (renders as checked="checked" for truthy, omits for falsy) tmpl5 = PageTemplate( '<input type="checkbox" tal:attributes="checked is_checked" />', boolean_attributes={"checked", "selected", "disabled"} ) print(tmpl5(is_checked=True)) # <input type="checkbox" checked="checked" /> print(tmpl5(is_checked=False)) # <input type="checkbox" /> # Error handling with tal:on-error tmpl6 = PageTemplate( '<p tal:content="risky" tal:on-error="string:Error occurred">placeholder</p>' ) print(tmpl6(risky="safe value")) # <p>safe value</p> ``` ``` -------------------------------- ### Load Template Instance Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Loads a template instance using the same template class as the calling template. This is useful for using templates as macros. ```xml <div tal:define="master load: ../master.pt" metal:use-macro="master" /> ``` -------------------------------- ### Debugging Templates with Python Debugger Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Illustrates using the Python debugger (pdb.set_trace()) within a template for debugging purposes. ```html <div> <?python import pdb; pdb.set_trace() ?> </div> ``` -------------------------------- ### Basic String Formatting Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Demonstrates basic string formatting using the 'string' TALES expression type. Variables are substituted using $name or ${expression}. ```xml <span tal:replace="string:$this and $that"> Spam and Eggs </span> ``` ```xml <p tal:content="string:${request.form['total']}"> total: 12 </p> ``` -------------------------------- ### Embedding Python Code in Templates Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Demonstrates embedding Python code within templates using the <?python ... ?> notation for dynamic content generation. ```html <div> <?python numbers = map(str, range(1, 10)) ?> Please input a number from the range ${', '.join(numbers)}. </div> ``` -------------------------------- ### Use Standard Python Expression for Uppercasing Source: https://github.com/malthe/chameleon/blob/master/docs/library.md An alternative to custom expressions, this shows using a standard Python string method within a template. ```html <div tal:content="'hello, world'.upper()" /> ``` -------------------------------- ### Tuple Unpacking in tal:define Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Supports tuple unpacking in tal:define statements. ```xml tal:define="(a, b, c) [1, 2, 3]" ``` -------------------------------- ### Macro with Slot Definition Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Defines a macro named 'hello' with a slot named 'name'. This slot provides a customization point for the macro's content. ```xml <p metal:define-macro="hello"> Hello <b metal:define-slot="name">World</b> </p> ``` -------------------------------- ### Tuple Unpacking in TAL Source: https://context7.com/malthe/chameleon/llms.txt Demonstrates tuple unpacking within a TAL attribute for iterating over items and assigning them to individual variables. ```python from chameleon import PageTemplate tmpl3 = PageTemplate(""" <ul tal:define="(first, second, third) items"> <li tal:content="first">a</li> <li tal:content="second">b</li> <li tal:content="third">c</li> </ul> """) print(tmpl3(items=["x", "y", "z"])) # <ul> # <li>x</li> # <li>y</li> # <li>z</li> # </ul> ``` -------------------------------- ### Basic XML Statement Syntax Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Illustrates the fundamental structure of a statement within the page templates language, using an XML tag with a namespace-prefixed command attribute. ```xml <p namespace-prefix:command="argument"> ... </p> ``` -------------------------------- ### File-based XML/HTML Template with PageTemplateFile Source: https://context7.com/malthe/chameleon/llms.txt Use PageTemplateFile to load templates from file paths. It supports the `load:` expression for referencing sibling templates and optional auto-reloading for development. File paths are normalized to absolute paths on construction. ```python import os from chameleon import PageTemplateFile # Load a template file (path must be absolute or will be made absolute) tmpl = PageTemplateFile("/srv/app/templates/page.pt") html = tmpl(title="My Page", user="Alice", items=["one", "two", "three"]) print(html) ``` ```python # Auto-reload during development (checks mtime on every render call) dev_tmpl = PageTemplateFile( "/srv/app/templates/page.pt", auto_reload=True ) ``` ```python # Load relative to a Python package (works inside zip archives too) pkg_tmpl = PageTemplateFile( "templates/page.pt", package_name="myapp" ) ``` -------------------------------- ### Load a Specific Template Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Load a template file relative to the configured templates directory using dictionary-like access. ```python template = templates['hello.pt'] ``` -------------------------------- ### String-based XML/HTML Template with PageTemplate Source: https://context7.com/malthe/chameleon/llms.txt Use PageTemplate to create templates directly from strings. The template is compiled on construction. Instances are callable, with keyword arguments becoming template variables. Supports auto-escaping, inline expressions, raw HTML rendering, and custom translation hooks. ```python from chameleon import PageTemplate # Basic variable substitution with auto-escaping tmpl = PageTemplate("<p>Hello, ${name}!</p>") print(tmpl(name="Alice")) # <p>Hello, Alice!</p> ``` ```python # Inline expressions in attribute values tmpl2 = PageTemplate( '<a href="/user/${user_id}" class="${\"active\" if active else \"\"}">Profile</a>' ) print(tmpl2(user_id=42, active=True)) # <a href="/user/42" class="active">Profile</a> ``` ```python # Raw/unescaped HTML with structure: prefix html_body = "<strong>Bold content</strong>" tmpl3 = PageTemplate("<div>${structure: body}</div>") print(tmpl3(body=html_body)) # <div><strong>Bold content</strong></div> ``` ```python # Rendering via .render() is identical to calling the instance result = tmpl.render(name="Bob") print(result) # <p>Hello, Bob!</p> ``` ```python # Custom translation hook passed at render time def my_translate(msgid, domain=None, mapping=None, context=None, target_language=None, default=None): catalog = {"Hello": "Hola"} return catalog.get(msgid, default or msgid) tmpl4 = PageTemplate('<p i18n:translate="">Hello</p>') print(tmpl4(translate=my_translate, target_language="es")) # <p>Hola</p> ``` ```python # Boolean attributes (renders as checked="checked" for truthy, omits for falsy) tmpl5 = PageTemplate( '<input type="checkbox" tal:attributes="checked is_checked" />', boolean_attributes={"checked", "selected", "disabled"} ) print(tmpl5(is_checked=True)) # <input type="checkbox" checked="checked" /> print(tmpl5(is_checked=False)) # <input type="checkbox" /> ``` ```python # Error handling with tal:on-error tmpl6 = PageTemplate( '<p tal:content="risky" tal:on-error="string:Error occurred">placeholder</p>' ) print(tmpl6(risky="safe value")) # <p>safe value</p> ``` -------------------------------- ### Configure PageTemplateLoader with Search Paths and Options Source: https://context7.com/malthe/chameleon/llms.txt PageTemplateLoader resolves and caches template files from specified directories. It supports dictionary-style access, default file extensions, and forwards keyword arguments to template constructors. ```python import os from chameleon import PageTemplateLoader # Single search path templates = PageTemplateLoader(os.path.join(os.path.dirname(__file__), "templates")) page = templates["page.pt"] print(page(title="Home", user="Alice")) # Multiple search paths (searched in order) templates = PageTemplateLoader([ "/srv/app/templates", "/srv/app/fallback_templates", ]) # Default extension — omit .pt in lookup keys templates = PageTemplateLoader("/srv/app/templates", default_extension=".pt") page = templates["page"] # loads page.pt layout = templates["layout"] # loads layout.pt # Pass constructor options to every template loaded templates = PageTemplateLoader( "/srv/app/templates", default_extension=".pt", boolean_attributes={"checked", "selected", "disabled", "readonly"}, auto_reload=True, # enable during development encoding="utf-8", ) # Load in text format text_loader = PageTemplateLoader( "/srv/app/templates", formats={"xml": ..., "text": ...} # use built-in defaults ) email_tmpl = text_loader.load("welcome.txt", format="text") print(email_tmpl(user="Alice")) # Template caching — loader caches loaded instances by filename page_a = templates["page"] page_b = templates["page"] assert page_a is page_b # same cached instance ``` -------------------------------- ### METAL Macro with i18n Domain Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Demonstrates how a METAL macro can be used with an i18n:domain attribute, showing lexical internationalization scoping. ```xml <html i18n:translate='' i18n:domain='EventsCalendar' metal:use-macro="container['master.html'].macros.thismonth"> <div metal:fill-slot='additional-notes'> <ol tal:condition="context.notes"> <li tal:repeat="note context.notes"> <tal:block tal:omit-tag="" tal:condition="note.heading"> <strong tal:content="note.heading"> Note heading goes here </strong> <br /> </tal:block> <span tal:replace="note/description"> Some longer explanation for the note goes here. </span> </li> </ol> </div> </html> ``` -------------------------------- ### XML Namespace Declarations for Templates Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Shows the standard XML namespace declarations required at the top of a template file for using TAL, METAL, and i18n features. ```xml <html xmlns="http://www.w3.org/1999/xhtml" xmlns:tal="http://xml.zope.org/namespaces/tal" xmlns:metal="http://xml.zope.org/namespaces/metal" xmlns:i18n="http://xml.zope.org/namespaces/i18n"> ... </html> ``` -------------------------------- ### Insert HTML/XML with tal:content Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Use `tal:content` with the `structure` keyword to insert HTML or XML content. This allows for marked-up content to be rendered directly, rather than being escaped as plain text. ```xml <p tal:content="structure context.getStory()"> Marked <b>up</b> content goes here. </p> ``` -------------------------------- ### Using lenient mode in PageTemplate Source: https://context7.com/malthe/chameleon/llms.txt Demonstrates how to use `strict=False` in `PageTemplate` to allow undefined variables to be rendered as 'nothing' (None) without raising an error. ```python from chameleon import PageTemplate lenient = PageTemplate( '<p tal:content="maybe_undefined_var | nothing">x</p>', strict=False ) print(lenient()) ``` -------------------------------- ### Define and Use a Macro in Chameleon Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Define a macro with slots and then use it, filling the slots with specific content. This is useful for creating reusable template components. ```xml <p metal:define-macro="hello"> Hello <b metal:define-slot="name">World</b> </p> ``` ```xml <p metal:use-macro="container['master.html'].macros.hello"> Hello <b metal:fill-slot="name">Kevin Bacon</b> </p> ``` -------------------------------- ### Dynamic Element Attributes with tal:attributes Source: https://context7.com/malthe/chameleon/llms.txt Demonstrates how to dynamically set, replace, or remove element attributes using `tal:attributes`. Evaluating an attribute to `None` removes it. The `default` keyword can preserve static template values. ```python from chameleon import PageTemplate tmpl = PageTemplate(""" <a href="/default" tal:attributes="href url; title tooltip; class css_class">Link</a> """) print(tmpl(url="/about", tooltip="About us", css_class="nav-link")) # <a href="/about" title="About us" class="nav-link">Link</a> # None drops the attribute entirely print(tmpl(url="/about", tooltip=None, css_class="nav-link")) # <a href="/about" class="nav-link">Link</a> ``` -------------------------------- ### Load Template with Default Extension Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Configure PageTemplateLoader to automatically append a default extension (e.g., '.pt') to template names that lack one. ```python templates = PageTemplateLoader(path, ".pt") example = templates['example'] ``` -------------------------------- ### METAL Macros for Reusable Template Components Source: https://context7.com/malthe/chameleon/llms.txt METAL macros enable defining reusable template fragments and using them across different templates. Use metal:define-macro to define and metal:use-macro to include. ```python # ---- /srv/app/templates/base.pt ---- # <html> # <head><title metal:define-slot="title">Default Title # #

My Site

#
#

Default content

#
#
© 2024
# # # (entire file is implicitly a macro accessible via template.macros['']) # ---- /srv/app/templates/page.pt ---- # # ${page_title} #
#

Title

#

Intro

#
# from chameleon import PageTemplateFile page = PageTemplateFile("/srv/app/templates/page.pt") print(page(page_title="About Us", intro="Learn more about our team.")) # # About Us # #

My Site

#
#

About Us

#

Learn more about our team.

#
#
© 2024
# # # Accessing a named macro from another template from chameleon import PageTemplate macros_tmpl = PageTemplate("""

Hello, World!

Goodbye, World!

""") user_tmpl = PageTemplate("""
unused
""") print(macros_tmpl.macros["greeting"].include) ``` -------------------------------- ### Iterate Over Strings with tal:repeat Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Use tal:repeat to iterate over a sequence of strings and display each one. ```xml

``` -------------------------------- ### PageTemplateFile - File-based XML/HTML template Source: https://context7.com/malthe/chameleon/llms.txt Loads a template from a file path. Adds the `load:` expression type for referencing sibling templates. Supports optional auto-reload on file modification (useful during development). The file path is normalized to an absolute path on construction. ```APIDOC ## PageTemplateFile ### Description Loads a template from a file path. Adds the `load:` expression type for referencing sibling templates. Supports optional auto-reload on file modification (useful during development). The file path is normalized to an absolute path on construction. ### Usage ```python import os from chameleon import PageTemplateFile # Load a template file (path must be absolute or will be made absolute) tmpl = PageTemplateFile("/srv/app/templates/page.pt") html = tmpl(title="My Page", user="Alice", items=["one", "two", "three"]) print(html) # Auto-reload during development (checks mtime on every render call) dev_tmpl = PageTemplateFile( "/srv/app/templates/page.pt", auto_reload=True ) # Load relative to a Python package (works inside zip archives too) pkg_tmpl = PageTemplateFile( "templates/page.pt", package_name="myapp" ) # A page.pt file that uses the load: expression to pull in a macro template: # ---- /srv/app/templates/page.pt ---- # # #
#

Title

#
    #
  • item
  • #
#
#
# ``` ``` -------------------------------- ### Load Expression Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Loads templates relative to the current template. ```xml
...
``` -------------------------------- ### Nested Iteration with Tuple Unpacking Source: https://context7.com/malthe/chameleon/llms.txt Illustrates nested iteration using `tal:repeat` with tuple unpacking for key-value pairs. This is useful for iterating over dictionaries or lists of tuples. ```python from chameleon import PageTemplate # Nested repeat with unpacking tmpl2 = PageTemplate("""
key val
""") print(tmpl2(pairs=[("host", "localhost"), ("port", 8080), ("debug", True)])) ``` -------------------------------- ### Unpack Sequence with tal:define Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Unpack elements from a sequence into multiple variables using parentheses in `tal:define`. This simplifies accessing individual items from lists or tuples. ```xml tal:define="(key,value) ('a', 42)" ``` -------------------------------- ### METAL Macro Source with Different Domain Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Shows the source of a METAL macro that uses a different i18n:domain than the calling template, illustrating lexical scoping. ```xml
January
Place for the application to add additional notes if desired.
``` -------------------------------- ### Define i18n Namespace Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Defines the i18n namespace URI and recommended prefix. This is a unique identifier and not a resolvable URL. ```xml xmlns:i18n="http://xml.zope.org/namespaces/i18n" ``` -------------------------------- ### Use File-Based Plain Text Template with PageTextTemplateFile Source: https://context7.com/malthe/chameleon/llms.txt PageTextTemplateFile is the file-based version of PageTextTemplate. Its render() method returns bytes (UTF-8 encoded by default). You can override the encoding. ```python from chameleon import PageTextTemplateFile # File-based text template (returns bytes) tmpl = PageTextTemplateFile("/srv/app/templates/report.txt") output_bytes = tmpl(title="Q4 Report", rows=[("Alice", 100), ("Bob", 200)]) # output_bytes is bytes, e.g. b"Q4 Report\n..." # Decode explicitly or write directly to a file with open("/tmp/report.txt", "wb") as f: f.write(output_bytes) # Override encoding tmpl_latin = PageTextTemplateFile( "/srv/app/templates/legacy.txt", encoding="latin-1" ) ``` -------------------------------- ### Conditional Rendering with tal:switch and tal:case Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Implement conditional logic using `tal:switch` and `tal:case`. `tal:switch` sets the expression to evaluate, and `tal:case` matches against specific values. The `default` case handles unmatched expressions. ```xml ``` ```xml ``` -------------------------------- ### Define a Custom Uppercase Expression Compiler Source: https://github.com/malthe/chameleon/blob/master/docs/library.md Create a closure that compiles a custom expression for uppercasing strings. This requires the `ast` module. ```python import ast def uppercase_expression(string): def compiler(target, engine): uppercased = self.string.uppercase() value = ast.Constant(uppercased) return [ast.Assign(targets=[target], value=value)] return compiler ``` -------------------------------- ### Merging Attributes from a Dictionary Source: https://context7.com/malthe/chameleon/llms.txt Shows how to merge a dictionary of attributes into an element dynamically using `tal:attributes`. This is useful for applying multiple attributes at once. ```python from chameleon import PageTemplate # Merging a dict of attributes dynamically tmpl2 = PageTemplate(""" """) print(tmpl2( input_type="text", attrs={"name": "username", "placeholder": "Enter username", "maxlength": "50"} )) # ``` -------------------------------- ### Insert Table Rows with tal:repeat Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Dynamically generate table rows by repeating over a sequence of items, using the repeat variable to number rows. ```xml
1 Widget $1.50
``` -------------------------------- ### Replace Element Content with tal:replace Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Replaces the content of an element with the result of an expression. Use 'structure' prefix for unescaped HTML. ```xml Title ``` ```xml
``` -------------------------------- ### TAL Switch/Case Control Flow Source: https://context7.com/malthe/chameleon/llms.txt Use tal:switch to set a comparison value and tal:case to conditionally render elements based on that value. The default case matches when no other case succeeds. ```python from chameleon import PageTemplate tmpl = PageTemplate("""

Account is active.

Account is suspended.

Account is banned.

Unknown status: ${status}

""") print(tmpl(status="active")) #
#

Account is active.

#
print(tmpl(status="pending")) #
#

Unknown status: pending

#
# Numeric switch tmpl2 = PageTemplate("""
  • Even number of items: ${len(items)}
  • Odd number of items: ${len(items)}
""") print(tmpl2(items=[1, 2, 3])) #
    #
  • Odd number of items: 3
  • #
``` -------------------------------- ### Specify Source Language with i18n:source Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Specifies the language of the text to be translated. Defaults to 'nothing' if not provided. ```xml Content ``` -------------------------------- ### Chameleon Exception Handling Source: https://context7.com/malthe/chameleon/llms.txt Demonstrates how to catch `TemplateError` (and its subclasses like `ParseError`, `CompilationError`, `LanguageError`, `ExpressionError`) during template compilation, and `RenderError` during rendering. `RenderError` provides detailed diagnostics including filename, line/column, expression, and variable scope. ```python from chameleon import PageTemplate from chameleon.exc import TemplateError, RenderError # Catch compilation errors (invalid template syntax) try: bad = PageTemplate('

x

') except TemplateError as e: print(f"Template error at line {e.location[0]}, col {e.location[1]}") print(f"Token: {e.token}") print(f"File: {e.filename}") # Catch render-time errors tmpl = PageTemplate('

x

') try: tmpl(divisor=0) except ZeroDivisionError as e: # RenderError is mixed into the exception class; check isinstance if isinstance(e, RenderError): # str(e) includes expression, filename, line/col and variable scope print("Render failed:", str(e)) else: raise # Strict vs. non-strict mode # strict=True (default): expression syntax is validated at compile time ``` -------------------------------- ### Define Global Variable with tal:define Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md Define a global variable using `tal:define` with the `global` keyword. Global variables are accessible throughout the remainder of the template after their definition. ```xml tal:define="global mytitle context.title; tlen len(mytitle)" ```