### 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
These are your items:
```
--------------------------------
### 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
```
--------------------------------
### 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("
Hello, ${name}.
")
output = template(name='John')
# output will be '
Hello, John.
'
```
```
--------------------------------
### 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("""
# Conditional tag stripping
tmpl2 = PageTemplate("""
I may or may not be bold.
""")
print(tmpl2(bold=True)) # I may or may not be bold.
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("
Hello, ${name}.
")
```
--------------------------------
### 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("""
```
--------------------------------
### 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("""
#
#
```
--------------------------------
### 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
Copyright 2011, Foobar Inc.
```
--------------------------------
### Import Expression
Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md
Imports module globals into the template namespace.
```xml
...
```
--------------------------------
### 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
1 * 1 = 1
```
--------------------------------
### 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
Content for value1Content for value2
```
--------------------------------
### 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("
Hello, ${name}!
")
print(tmpl(name="Alice"))
#
Hello, Alice!
# Inline expressions in attribute values
tmpl2 = PageTemplate(
'Profile'
)
print(tmpl2(user_id=42, active=True))
# Profile
# Raw/unescaped HTML with structure: prefix
html_body = "Bold content"
tmpl3 = PageTemplate("
${structure: body}
")
print(tmpl3(body=html_body))
#
Bold content
# Rendering via .render() is identical to calling the instance
result = tmpl.render(name="Bob")
print(result)
#
Hello, Bob!
# 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('
# Boolean attributes (renders as checked="checked" for truthy, omits for falsy)
tmpl5 = PageTemplate(
'',
boolean_attributes={"checked", "selected", "disabled"}
)
print(tmpl5(is_checked=True))
#
print(tmpl5(is_checked=False))
#
# Error handling with tal:on-error
tmpl6 = PageTemplate(
'
placeholder
'
)
print(tmpl6(risky="safe value"))
#
safe value
```
```
--------------------------------
### 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
```
--------------------------------
### 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
```
--------------------------------
### 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
Spam and Eggs
```
```xml
total: 12
```
--------------------------------
### Embedding Python Code in Templates
Source: https://github.com/malthe/chameleon/blob/master/docs/reference.md
Demonstrates embedding Python code within templates using the notation for dynamic content generation.
```html
Please input a number from the range ${', '.join(numbers)}.
```
--------------------------------
### 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
```
--------------------------------
### 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
Hello World
```
--------------------------------
### 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("""
a
b
c
""")
print(tmpl3(items=["x", "y", "z"]))
#
#
x
#
y
#
z
#
```
--------------------------------
### 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
...
```
--------------------------------
### 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("
```
```python
# Boolean attributes (renders as checked="checked" for truthy, omits for falsy)
tmpl5 = PageTemplate(
'',
boolean_attributes={"checked", "selected", "disabled"}
)
print(tmpl5(is_checked=True))
#
print(tmpl5(is_checked=False))
#
```
```python
# Error handling with tal:on-error
tmpl6 = PageTemplate(
'
placeholder
'
)
print(tmpl6(risky="safe value"))
#
safe value
```
--------------------------------
### 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
Note heading goes here
Some longer explanation for the note goes here.
```
--------------------------------
### 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
...
```
--------------------------------
### 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
Marked up content goes here.
```
--------------------------------
### 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(
'
x
',
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
Hello World
```
```xml
Hello Kevin Bacon
```
--------------------------------
### 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("""
Link
""")
print(tmpl(url="/about", tooltip="About us", css_class="nav-link"))
# Link
# None drops the attribute entirely
print(tmpl(url="/about", tooltip=None, css_class="nav-link"))
# Link
```
--------------------------------
### 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 ----
#
# Default Title
#
#
My Site
#
#
Default content
#
#
#
#
# (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.
#
#
#
#
# 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
odd
even
```
```xml
Document
Folder
Other
```
--------------------------------
### 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)"
```