---------------------------------------------------------------------- This is the API documentation for the chameleon_robyn library. ---------------------------------------------------------------------- ## Setup & configuration Initialize the template engine once at app startup. global_init(template_folder: str, auto_reload: bool = False, cache_init: bool = True, restricted_namespace: bool = True) -> None Initialize the Chameleon template engine. Call this once at startup, before the first request is rendered. Routes may be decorated with `@template` before this runs; auto-named templates are resolved lazily at the first request. Args: template_folder: Path to the template directory. All template paths passed to `@template`, render(), response() and not_found() are relative to this folder. auto_reload: Whether to re-read templates when they change on disk. Use True in development only; it disables caching. cache_init: If True (the default) and the engine is already initialized, the call is ignored and the earlier settings stay in effect. Pass False to re-initialize with new settings (tests do this), or call clear() first. restricted_namespace: If True, only TAL/METAL/i18n namespaces are allowed in attributes. If False, attribute-based JS frameworks like Alpine.js and htmx can use shorthand syntax (`@click`, :class, etc.). Raises: ChameleonRobynException: If template_folder is empty or is not an existing directory. Examples: ```python from pathlib import Path import chameleon_robyn templates = (Path(__file__).resolve().parent / 'templates').as_posix() chameleon_robyn.global_init(templates, auto_reload=True) # auto_reload for development only ``` clear() -> None Reset the template engine to its uninitialized state. After calling this, global_init() must be called again before rendering. Mostly useful in tests to isolate template configuration between cases. Examples: ```python import pytest import chameleon_robyn @pytest.fixture def templates(tmp_path): chameleon_robyn.global_init(str(tmp_path), cache_init=False) yield chameleon_robyn.clear() ``` ## Rendering views The `@template` decorator and friendly 404s for Robyn route handlers. template(template_file: Callable | str | None = None, content_type: str = 'text/html', status_code: int = 200) -> Callable Decorate a Robyn view method to render an HTML response. The decorated handler returns a dict (the template model). If the template path is omitted, it is derived from the module and function name: module/function.html if that file exists, otherwise module/function.pt. For a script run directly (module __main__) the script's file name is used instead, so index() in app.py maps to app/index.pt; a legacy __main__/function.html or .pt is still found if the script-named file does not exist. The auto-derived name is resolved at first request, so global_init() may be called after route decoration. Handlers that return a Robyn Response are passed through untouched (redirects, custom errors). Works with sync and async handlers. Place `@template` directly above the handler, below Robyn's route decorator. Args: template_file: Optional, the Chameleon template file (path relative to template folder, *.pt). content_type: The Content-Type header value for rendered responses (defaults to text/html). status_code: The HTTP status code for rendered responses (defaults to 200). Returns: Decorator for Robyn route handlers. Raises: ChameleonRobynException: At request time, if the handler returns something other than a dict or a Robyn Response, or if '__response_callback__' is not callable. Examples: ```python @app.get('/episodes/:episode_id') @chameleon_robyn.template('episodes/detail.pt') async def episode_detail(request, episode_id: int): return {'episode': await get_episode(episode_id)} @app.get('/') @chameleon_robyn.template # renders /index.html or /index.pt def index(request): return {'title': 'Home'} ``` not_found(four04template_file: str = 'errors/404.pt') -> NoReturn Render a friendly 404 page from within a `@template`-decorated handler. Raises an exception that the `@template` decorator catches and converts into a 404 response rendered through the given template. The template receives a `message` variable describing the 404. Only works inside handlers decorated with `@template`. Args: four04template_file: The template to render, relative to the template folder (defaults to 'errors/404.pt'). Raises: ChameleonRobynNotFoundException: Always; carries the 404 template path. Examples: ```python @app.get('/episodes/:episode_id') @chameleon_robyn.template('episodes/detail.pt') def episode_detail(request, episode_id: int): episode = get_episode(episode_id) if not episode: chameleon_robyn.not_found() # renders errors/404.pt with status 404 return {'episode': episode} ``` ## Lower-level rendering Render templates outside the decorator (middleware, error handlers, emails). render(template_file: str, **template_data: Any) -> str Render a Chameleon template to a string (no Response wrapping). Useful outside of route handlers: emails, middleware, error handlers, etc. Args: template_file: The template file path, relative to the template folder (e.g. 'emails/welcome.pt'). **template_data: Values passed to the template as its model. The key 'encoding' is reserved by Chameleon and cannot be used. Returns: The rendered template as a string. Raises: ChameleonRobynException: If global_init() has not been called, or the model uses the reserved key 'encoding'. ValueError: Raised by Chameleon when the template file does not exist. Examples: ```python html = chameleon_robyn.render('emails/welcome.pt', username='Michael') ``` response(template_file: str, content_type: str = 'text/html', status_code: int = 200, **template_data: Any) -> Response Render a Chameleon template and wrap it in a fully-formed Robyn Response. Useful where the `@template` decorator does not fit: error handlers, middleware, or a handler that renders different templates depending on the request. Args: template_file: The template file path, relative to the template folder. content_type: The Content-Type header value (defaults to text/html). status_code: The HTTP status code for the response (defaults to 200). **template_data: Values passed to the template as its model. Returns: A Robyn Response with the rendered template as its body. Raises: ChameleonRobynException: If global_init() has not been called, or the model uses the reserved key 'encoding'. Examples: ```python resp = chameleon_robyn.response('errors/500.pt', status_code=500, error=str(e)) ``` ## Robyn TemplateInterface Standalone template engine class matching Robyn's built-in template pattern. ChameleonTemplate(directory: str, auto_reload: bool = False, encoding: str = 'utf-8', restricted_namespace: bool = True) Chameleon template engine implementing Robyn's TemplateInterface. A standalone alternative to the module-level API: it owns its own template loader and does not require global_init(). Use it like Robyn's built-in JinjaTemplate. Args: directory: Path to the template directory. auto_reload: Whether to auto-reload templates on change (use True in development). encoding: Output encoding for rendered templates (defaults to utf-8). restricted_namespace: If True, only TAL/METAL/i18n namespaces are allowed. Set to False for Alpine.js/htmx-style attributes (`@click`, :class, etc.). Examples: ```python from chameleon_robyn import ChameleonTemplate chameleon = ChameleonTemplate('templates/', auto_reload=True) @app.get('/page') def page(request): return chameleon.render_template('page.pt', title='Hello') ``` ## Exceptions Exception types raised by the library. ChameleonRobynException Base exception for all chameleon-robyn errors (bad configuration, invalid return types, etc.). Examples: ```python try: chameleon_robyn.render('home/index.pt', title='Home') except chameleon_robyn.ChameleonRobynException as e: log.error('template setup problem: %s', e) ``` ChameleonRobynNotFoundException(message: str | None = None, four04template_file: str = 'errors/404.pt') Raised by not_found() to signal a 404 from within a `@template`-decorated handler. The `@template` decorator catches this exception and renders the template it carries with a 404 status code, passing the message to the template as `message`. Args: message: Optional human-readable description of the 404. four04template_file: The 404 template to render, relative to the template folder. Examples: Raise it directly to supply your own message to the 404 template: ```python raise ChameleonRobynNotFoundException(f'No episode with id {episode_id}.') ``` ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Get started ### Getting started Every web framework eventually asks the same question: how do you turn data into HTML? Robyn's answer out of the box is Jinja2. This package offers a second answer, the one people who built on Pyramid or Zope tend to miss the moment they leave: [Chameleon](https://chameleon.readthedocs.io/) page templates. A Chameleon template is an ordinary HTML file. Open one in a browser before it has ever been rendered and you still see a page, placeholders and all, because the logic lives inside attributes the browser ignores. `tal:repeat` loops, `tal:condition` hides, and `${...}` fills in values with real Python expressions. There is no second language layered over your markup. Your designer can open the file. Your editor can validate it. And chameleon-robyn wires those templates into Robyn with a single decorator: your handler returns a `dict`, and a rendered `Response` comes out the other side. One honest note before we begin: the project is in alpha. The API is small and unlikely to change much, but there are no stability promises yet. ## Install ```bash uv pip install chameleon-robyn ``` Or with pip: ```bash pip install chameleon-robyn ``` This brings in `robyn` and `chameleon` as dependencies. Python 3.10 or newer is required. ## The site we are building This guide follows one project from the first page to the last error message: the website for a small podcast. It has an episode list, a page per episode, a guest directory, a search box, an XML feed for the robots, and the occasional visitor who types a URL that does not exist. Every snippet in the guide comes from that site, and the repository's `example/` folder holds the finished version. ## Project layout Nothing about the layout is enforced, but this is the shape that makes the rest of the guide read naturally: ```text my_app/ ├── app.py └── templates/ └── home/ └── index.pt ``` Every template path you hand the library is relative to the `templates/` folder you register at startup. The folder name is yours to choose. ## Your first page Start with `templates/home/index.pt`. Notice that it is just HTML with two extra ideas: `${name}` to drop in a value, and `tal:repeat` on the element that should repeat. ```xml

Hello, ${name}!

``` Now `app.py`. Three lines matter: the import, the `global_init()` call that says where templates live, and the decorator above the handler. ```python from pathlib import Path from robyn import Robyn import chameleon_robyn app = Robyn(__file__) # Point Chameleon at your templates folder (do this once at startup) template_folder = (Path(__file__).resolve().parent / 'templates').as_posix() chameleon_robyn.global_init(template_folder, auto_reload=True) @app.get('/') @chameleon_robyn.template('home/index.pt') async def index(request): return {'name': 'World', 'items': ['Robyn', 'Chameleon', 'Python']} app.start(host='127.0.0.1', port=8000) ``` Run `python app.py` and open . A heading and a three-item list greet you. That handler never touched a string of HTML, and it never will. ## What just happened - `global_init()` told Chameleon where the templates live. It runs once at startup, and its settings are the subject of [Configuration](configuration.qmd). - `@template('home/index.pt')` wrapped the handler. The handler returned a `dict`, and every key in it became a variable the template could see. - The decorator rendered the template and handed back a Robyn `Response` with status 200 and a `Content-Type` of `text/html; charset=utf-8`. - Robyn's route decorator stayed on the outside. `@template` sits directly above the function, and it is equally happy with `def` and `async def`. That is the whole mental model. Everything else in this guide is a refinement of it. ## Run the finished examples Two runnable apps live in the repository. The first shows every feature on the podcast site: episodes and guests, a shared METAL layout, search by query string, the XML feed, a redirect, a cookie set from a rendered page, and a friendly 404. The second is the same app with the episode card pulled out into a reusable partial. ```bash git clone https://github.com/mikeckennedy/chameleon-robyn.git cd chameleon-robyn python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -e ".[examples]" python example/app.py # core features python example-partials/app.py # the same app using chameleon-partials # Open http://127.0.0.1:5555 ``` ## Where to go next - [The @template decorator](template-decorator.qmd): the return-value contract, templates that name themselves, async handlers, status codes, redirects, and setting a cookie on a rendered page. - [Writing templates](templates.qmd): a TAL cheat sheet, shared layouts with METAL, escaping, Alpine.js and htmx attributes, and chameleon-partials. - [Friendly 404 pages](not-found.qmd): one call to `not_found()` and the stack trace never reaches the visitor. - [Rendering outside handlers](lower-level-api.qmd): `render()`, `response()`, and the standalone `ChameleonTemplate` class. - [Configuration](configuration.qmd): every `global_init()` setting, and the one that bites people in tests. - [Testing your handlers](testing.qmd): no server, no client, just function calls. - [Errors and how to fix them](troubleshooting.qmd): a field guide to every exception you can meet. - [How it works](how-it-works.qmd): a tour of the three source files. - [FAQ](faq.qmd) - [API reference](../reference/index.qmd) ### The @template decorator A route handler has two jobs: decide what to show, and show it. `@template` takes the second job away entirely. Your handler gathers data and returns a `dict`. The decorator finds the template, renders it, builds the `Response`, and sets the headers. You never see a string of HTML in Python again, and the handler reads like a description of the page rather than a construction of it. ## The contract Everything the decorator does follows from one rule about what your handler returns: | Handler returns | What the decorator does | |---|---| | a `dict` | Renders the template with the dict as its variables and returns a 200 `Response` (or the status you configured). | | a Robyn `Response` | Returns it untouched. No template is rendered. This is the escape hatch for redirects and hand-built responses. | | anything else | Raises `ChameleonRobynException` at request time. `None`, strings and numbers are all rejected. | Return the dict directly. The decorator copies it before rendering, so returning a shared or module-level dict is safe. ## Explicit template path The podcast's episode list is the plainest possible case: ```python @app.get('/episodes') @chameleon_robyn.template('episodes/list.pt') def episode_list(request): return {'episodes': get_all_episodes()} ``` The path is relative to the folder passed to `global_init()`. Any file extension works; `.pt` is the convention, and the same site renders a `.xml` feed with the same decorator. ## Auto-naming {#auto-naming} Leave the path out and the decorator names the template after the code that renders it. The rule has three steps: 1. Take the last segment of the handler's module name and the function name. 2. Look for `/.html` under the template folder. 3. If that file does not exist, use `/.pt`. So `index()` in `views/home_views.py` renders `home_views/index.html` if it exists, otherwise `home_views/index.pt`. Your template folder ends up mirroring your view modules, which is a pleasant thing to discover six months later. ```python # Looks for templates/home_views/index.pt @app.get('/') @chameleon_robyn.template() def index(request): return {'message': 'Hello!'} ``` The parentheses are optional: ```python @app.get('/') @chameleon_robyn.template def index(request): return {'message': 'Hello!'} ``` Two details are worth knowing: - A script run directly (`python app.py`) has the module name `__main__`, which would make for a strange folder name. The library uses the script's file name instead, so `index()` in `app.py` maps to `app/index.pt`. If no such file exists but `__main__/index.html` or `__main__/index.pt` does, that is used, so apps built on the old behavior keep working. - The name is resolved at the first request, not when the decorator runs. That is what lets you decorate routes at import time and call `global_init()` later from `main()`. The file only has to exist by the time the first visitor arrives. ## Async handlers Nothing to configure. The decorator notices `async def` and awaits the handler, so the episode page can go to the database like any other coroutine: ```python @app.get('/dashboard') @chameleon_robyn.template('dashboard.pt') async def dashboard(request): stats = await fetch_stats_from_db() return {'stats': stats} ``` Robyn's typed path parameters pass straight through: ```python @app.get('/episodes/:episode_id') @chameleon_robyn.template('episodes/detail.pt') async def episode_detail(request, episode_id: int): return {'episode': await get_episode(episode_id)} ``` ## Status codes and content types Templates are not only for HTML pages. The podcast feed is a Chameleon template too, and so is a "created" page after a form post: ```python # Return a 201 after creating a resource @app.post('/items') @chameleon_robyn.template('items/created.pt', status_code=201) async def create_item(request): item = await save_item(request.json()) return {'item': item} # Serve an XML feed @app.get('/feed.xml') @chameleon_robyn.template('episodes/feed.xml', content_type='application/xml') def xml_feed(request): return {'episodes': get_recent_episodes()} ``` The `charset=utf-8` suffix is added to the content type for you. These settings apply to rendered responses only. A pass-through `Response` keeps its own status and headers, and a 404 from `not_found()` always renders as `text/html` with status 404. ## Redirects and other pass-through responses Sometimes the right answer is not a page at all. Return a Robyn `Response` and the decorator steps aside: ```python from robyn import Response, Headers @app.get('/old-page') @chameleon_robyn.template('home/index.pt') def old_page(request): return Response( status_code=302, description='', headers=Headers({'Location': '/new-page'}), ) ``` The same rule lets one handler choose between templates at runtime: build the alternative with [`response()`](lower-level-api.qmd) and return it. ## Setting cookies or headers on a rendered page {#setting-cookies-or-headers-on-a-rendered-page} Here is the classic puzzle. A visitor logs in. You want to render the welcome page, which means returning a dict, and you also want to set a session cookie, which means touching the `Response`. You cannot do both from a dict. Or can you? Put a callable under the reserved key `__response_callback__` in the returned dict. After rendering, the decorator calls it with the `Response` it just built: ```python from robyn import Response @app.post('/account/login') @chameleon_robyn.template('account/welcome.pt') async def login(request): user = await authenticate(request) if not user: return chameleon_robyn.response('account/login_failed.pt', status_code=401) token = create_session_token(user) def set_session_cookie(resp: Response): resp.headers.append('Set-Cookie', f'session={token}; HttpOnly; Path=/') return { 'user': user, '__response_callback__': set_session_cookie, } ``` Rules for the callback: - It is removed from the model before rendering, so the template never sees it, and your dict is not modified. - Change the `Response` in place. The return value is ignored. - It must be callable. Anything else raises `ChameleonRobynException`. ## Decorator order Robyn's route decorator goes on the outside and `@template` goes directly above the function. Robyn reads the handler's signature when the route is registered, and the decorator preserves the original signature, so `request` and path parameters keep flowing exactly as they did before. ```python @app.get('/episodes') # outermost @chameleon_robyn.template('episodes/list.pt') # directly above the function def episode_list(request): ... ``` ### Writing templates Most template languages ask you to learn a second syntax and sprinkle it through your HTML. Chameleon asks you to learn a handful of attributes. A template is always a well-formed document, and every loop and condition attaches to the element it controls. The result is markup you can read top to bottom and know exactly which element repeats, which disappears, and where the data lands. The full language reference lives at [chameleon.readthedocs.io](https://chameleon.readthedocs.io/); this page covers the parts the podcast site needs. ## TAL cheat sheet {#tal-cheat-sheet} ```xml

${title}

${user.name.title()} has ${len(items)} item(s)

Special offer!
Nothing here yet.
  • ${item.name} - $${item.price}
  • ${repeat.row.number}. ${row.title} ${item.name} ${item.name} placeholder shown in a browser preview 2024-01-01 Total: ${total} ``` Two habits pay off quickly. First, the placeholder text inside `tal:content` and `tal:replace` is what you see when you open the file in a browser without rendering it, so write something realistic there. Second, a literal `$` followed by `{` is written `$${...}`, as in the price example above. ## Escaping and `structure` Everything inserted with `${...}`, `tal:content` or `tal:replace` is HTML-escaped. A guest named `