Metadata-Version: 2.4
Name: pytera
Version: 0.1.1
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Rust
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Markup :: HTML
Classifier: Topic :: Text Processing :: Markup :: XML
Summary: A fast, Python templating engine powered by Rust's Tera library
Keywords: templating,tera,rust,pyo3,jinja2,django-templates,web-framework,html,rendering,fast
Author-email: un4gt <mt3085570450@outlook.com>
Maintainer-email: un4gt <mt3085570450@outlook.com>
License: MIT
Requires-Python: >=3.8.1
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/PyO3Lab/pytera
Project-URL: Documentation, https://github.com/PyO3Lab/pytera#readme
Project-URL: Repository, https://github.com/PyO3Lab/pytera.git
Project-URL: Issues, https://github.com/PyO3Lab/pytera/issues
Project-URL: Changelog, https://github.com/PyO3Lab/pytera/blob/main/CHANGELOG.md

# PyTera

[![PyPI version](https://badge.fury.io/py/pytera.svg)](https://pypi.org/project/pytera/)
[![Python versions](https://img.shields.io/pypi/pyversions/pytera.svg)](https://pypi.org/project/pytera/)
[![License](https://img.shields.io/pypi/l/pytera.svg)](https://github.com/un4gt/pytera/blob/main/LICENSE)
[![CI](https://github.com/un4gt/pytera/actions/workflows/ci.yml/badge.svg)](https://github.com/un4gt/pytera/actions/workflows/ci.yml)
[![Codecov](https://codecov.io/gh/un4gt/pytera/branch/main/graph/badge.svg)](https://codecov.io/gh/un4gt/pytera)

A fast, Python-native templating engine powered by Rust's Tera library. PyTera brings the power and performance of Tera templates to Python applications through PyO3 bindings.

## Features

- 🚀 **High Performance**: Rust-powered templating with zero-copy operations
- 🐍 **Python Native**: Seamless integration with Python data types and workflows
- 📝 **Tera Compatible**: Full support for Tera template syntax and features
- 🔧 **Easy Integration**: Simple API that works with Flask, FastAPI, and other web frameworks
- 🛡️ **Type Safe**: Comprehensive type hints and error handling
- 📚 **Rich Features**: Variables, conditionals, loops, filters, inheritance, and more

## Installation

Install PyTera from PyPI:

```bash
pip install pytera
```

Or using uv:

```bash
uv add pytera
```

### Requirements

- Python 3.8+
- Rust toolchain (for building from source)

## Quick Start

```python
from pytera import PyTera

# Initialize with template directory
tera = PyTera("templates/*.html")

# Render a template
result = tera.render_template("hello.html", {"name": "World"})
print(result)  # Hello World!
```

## Usage Examples

### Basic Variables

```python
from pytera import PyTera

tera = PyTera("templates/*.html")
result = tera.render_template("basic_variables.html", {
    "name": "Alice",
    "age": 30
})
# Output: Hello Alice! You are 30 years old.
```

### Conditionals

```python
user = {"name": "Bob", "is_admin": True}
result = tera.render_template("conditionals.html", {"user": user})
# Output: Welcome, Administrator Bob!
```

### Loops

```python
items = [
    {"name": "Apple", "price": 1.50},
    {"name": "Banana", "price": 0.75},
    {"name": "Cherry", "price": 2.25},
]
result = tera.render_template("loops.html", {"items": items})
```

### Filters

```python
data = {
    "text": "hello world",
    "missing": None,
    "list": ["apple", "banana", "cherry", "date"],
}
result = tera.render_template("filters.html", data)
```

### Template Inheritance

```python
# base.html
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
    <h1>My Website</h1>
    {% block content %}{% endblock %}
</body>
</html>

# child.html
{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
<h2>Welcome to {{ site_name }}</h2>
<p>Hello, {{ user.name }}!</p>
{% endblock %}
```

### Flask Integration

```python
from flask import Flask
from pytera import PyTera

app = Flask(__name__)
tera = PyTera("templates/*.html")

@app.route("/")
def index():
    return tera.render_template(
        "page.html",
        {"site_name": "My Site", "user": {"name": "David"}}
    )

if __name__ == "__main__":
    app.run()
```

## API Reference

### PyTera Class

#### `__init__(glob: str)`

Initialize PyTera with a template glob pattern.

**Parameters:**
- `glob` (str): Glob pattern for template files (e.g., `"templates/**/*.html"`)


**Raises:**
- `ValueError`: Invalid glob pattern or template configuration errors
- `RuntimeError`: Template parsing failures or inheritance issues
- `UnicodeDecodeError`: UTF-8 decoding errors
- `OSError`: File I/O errors

#### `render_template(template: str, kwargs: Optional[Mapping[str, Any]] = None) -> str`

Render a template with the given context.

**Parameters:**
- `template` (str): Template name/key
- `kwargs` (Optional[Mapping[str, Any]]): Context dictionary

**Returns:**
- `str`: Rendered template content

**Raises:**
- `ValueError`: Invalid context keys or configuration errors
- `RuntimeError`: Template rendering errors
- `UnicodeDecodeError`: Encoding errors
- `OSError`: File I/O errors

#### `templates() -> list[str]`

Get list of loaded template names.

**Returns:**
- `list[str]`: Template names

## Template Syntax

PyTera supports the full Tera template syntax:

### Variables
```
{{ variable }}
{{ user.name }}
```

### Conditionals
```
{% if condition %}
Content here
{% elif other_condition %}
Other content
{% else %}
Default content
{% endif %}
```

### Loops
```
{% for item in items %}
{{ item.name }}: {{ item.price }}
{% endfor %}
```

### Filters
```
{{ text | upper }}
{{ number | round(precision=2) }}
{{ list | slice(start=1, end=3) | join(sep=", ") }}
```

### Template Inheritance
```
<!-- base.html -->
{% block content %}{% endblock %}

<!-- child.html -->
{% extends "base.html" %}
{% block content %}Child content{% endblock %}
```

## Error Handling

PyTera provides detailed error messages for common issues:

- **Template Not Found**: When requesting a non-existent template
- **Invalid Context**: When context keys aren't strings
- **Parsing Errors**: Syntax errors in templates
- **Inheritance Issues**: Circular dependencies or missing parents

## Performance

PyTera is designed for high performance:

- Zero-copy string operations in Rust
- Efficient template compilation and caching
- Minimal Python overhead through PyO3

## Development

### Building from Source

```bash
# Clone the repository
git clone https://github.com/un4gt/pytera.git
cd pytera

# Install development dependencies
uv sync --dev

# Build the package
maturin develop

# Run tests
pytest
```

### Running Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=pytera --cov-report=html
```

### Code Quality

```bash
# Format code
cargo fmt
black src/

# Lint code
cargo clippy
flake8 src/
```

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

### Development Setup

```bash
# Install development dependencies
uv sync --dev

# Install pre-commit hooks
pre-commit install

# Build and test
maturin develop
pytest
```

## License

PyTera is licensed under the MIT License. See [LICENSE](LICENSE) for details.

## Acknowledgments

- [Tera](https://keats.github.io/tera/) - The Rust templating engine
- [PyO3](https://pyo3.rs/) - Python bindings for Rust
- [Maturin](https://www.maturin.rs/) - Build tool for Python extensions

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history.
