### kamidana with Additionals Module Example
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Shows how to use kamidana with the `--additionals` option to leverage built-in naming convention filters. This example demonstrates singularization, pluralization, and case conversion.
```console
$ kamidana --additionals=kamidana.additionals.naming examples/readme/src/01/use-naming.jinja2
singular, plurals
- days|singularize -> day
- day|pluralize -> days
- people|singularize -> person
- person|pluralize -> people
to {snake_case, kebab-case, camelCase}
- fooBarBoo|snakecase -> foo_bar_boo
- fooBarBoo|kebabcase -> foo-bar-boo
- foo_bar_boo|camelcase -> fooBarBoo
more information: see kamidana.additionals.naming module
```
--------------------------------
### Use Built-in 'scream' Example
Source: https://context7.com/podhmo/kamidana/llms.txt
Demonstrates using a custom filter defined in a local Python file with Kamidana.
```bash
$ kamidana -a scream.py src/04relative.jinja2
# Template: {{"hello"|scream}}
# Output: HELLO!!
```
--------------------------------
### Basic kamidana Rendering Example
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Renders an Nginx configuration file using a Jinja2 template and a JSON data file. This demonstrates the fundamental usage of kamidana.
```console
$ kamidana examples/readme/src/00/nginx.jinja2 --data examples/readme/src/00/data.json
server {
listen 80;
server_name localhost;
root /var/www/project;
index index.htm;
access_log /var/log/nginx/http.access.log combined;
error_log /var/log/nginx/http.error.log;
}
```
```jinja2
server {
listen 80;
server_name {{ nginx.hostname }};
root {{ nginx.webroot }};
index index.htm;
access_log {{ nginx.logdir }}/http.access.log combined;
error_log {{ nginx.logdir }}/http.error.log;
}
```
```json
{
"nginx": {
"hostname": "localhost",
"webroot": "/var/www/project",
"logdir": "/var/log/nginx"
}
}
```
--------------------------------
### Custom Rendering Driver for Uppercasing Output
Source: https://context7.com/podhmo/kamidana/llms.txt
Create a custom driver by subclassing `kamidana.driver.Driver` and overriding the `transform` method to modify the rendered output. This example converts all output to uppercase.
```python
# custom_driver.py — a driver that uppercases all output
from kamidana.driver import Driver
class UpperDriver(Driver):
def transform(self, t):
result = super().transform(t)
return result.upper()
```
--------------------------------
### Include Directive with Missing Template
Source: https://github.com/podhmo/kamidana/blob/master/examples/basic/dst/02/include-notfound.html
This example shows multiple {% include %} directives attempting to render a template named 'missing-404.j2', which is not present. Kamidana will raise an XTemplatePathNotFound error.
```html
{% with name="xxx" %}
{% with name="foo" %}{% include "missing-404.j2" %}{% endwith %}
{% with name="bar" %}{% include "missing-404.j2" %}{% endwith %}
{% with name="boo" %}{% include "missing-404.j2" %}{% endwith %}
{% include "missing-404.j2" %}
```
--------------------------------
### kamidana Gentle Error Message Example
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Illustrates kamidana's gentle error handling when an included template is not found. The output shows the error message, the location of the error, and a traceback.
```console
$ tree examples/readme/src/11
examples/readme/src/11
├── header.html.j2
└── main.html.j2
1 directory, 2 files
```
```console
$ kamidana examples/readme/src/11/main.html.j2
------------------------------------------------------------
exception: kamidana._path.XTemplatePathNotFound
message: [Errno 2] No such file or directory: 'footer-404.html.j2'
where: examples/readme/src/11/main.html.j2
------------------------------------------------------------
examples/readme/src/11/main.html.j2:
2:
3: this is main contents
4:
-> 5: {% include "footer-404.html.j2" %}
Traceback:
File "SITE-PACKAGES/jinja2/loaders.py", line 462, in get_source
rv = self.load_func(template)
File "HERE/me/kamidana/kamidana/loader.py", line 27, in load
raise XTemplatePathNotFound(filename, exc=e).with_traceback(e.__traceback__)
File "HERE/me/kamidana/kamidana/loader.py", line 23, in load
with open(filename) as rf:
```
--------------------------------
### Example of XTemplatePathNotFound Error
Source: https://github.com/podhmo/kamidana/blob/master/examples/readme/dst/11/error-include-404.html
This snippet illustrates the traceback and error message generated when Kamidana attempts to include a template file that does not exist. The error occurs at line 5 of 'src/11/main.html.j2' due to the missing 'footer-404.html.j2'.
```html
Project: /podhmo/kamidana
Content:
------------------------------------------------------------ exception: kamidana._path.XTemplatePathNotFound message: [Errno 2] No such file or directory: 'footer-404.html.j2' where: src/11/main.html.j2 ------------------------------------------------------------ src/11/main.html.j2: 2:
3: this is main contents 4:
-> 5: {% include "footer-404.html.j2" %} Traceback:
File "SITE-PACKAGES/jinja2/loaders.py", line 462, in get_source
rv = self.load_func(template)
File "HERE/kamidana/loader.py", line 27, in load
raise XTemplatePathNotFound(filename, exc=e).with_traceback(e.__traceback__)
File "HERE/kamidana/loader.py", line 23, in load
with open(filename) as rf:
```
--------------------------------
### Division by Zero Example
Source: https://github.com/podhmo/kamidana/blob/master/examples/basic/dst/03/zero.div.html
This snippet shows a direct division by zero operation. Ensure that all divisions are safe to prevent runtime errors.
```html
1 / 0 = {{ 1 / 0 }}
```
--------------------------------
### Custom Template Loader with Header Injection
Source: https://context7.com/podhmo/kamidana/llms.txt
Subclass `kamidana.loader.TemplateLoader` to pre-process template source. This example injects a header comment into the loaded template content.
```python
# examples/customize/src/00/loader.py
from kamidana.loader import TemplateLoader
class WithHeaderLoader(TemplateLoader):
def load(self, filename):
buf = []
buf.append("# this file is auto generated by {!r}.\n\n".format(filename))
source, filename, _ = super().load(filename)
buf.append(source)
return "".join(buf), filename, None
```
--------------------------------
### List available extensions and additional modules
Source: https://context7.com/podhmo/kamidana/llms.txt
Lists all available Jinja2 extensions and Kamidana additional modules that can be used with the tool.
```bash
# List all available extensions and additional modules
$ kamidana --list-info
```
--------------------------------
### List Available Kamidana Extensions and Modules
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Command to list all available Jinja2 extensions and Kamidana additional modules, along with their descriptions.
```console
$ kamidana --list-info
extensions are used by `-e`, additional modules are used by `-a`.
{
"extensions": {
"jinja2.ext.i18n": "This extension adds gettext support to Jinja.",
"jinja2.ext.do": "Adds a `do` tag to Jinja that works like the print statement just",
"jinja2.ext.loopcontrols": "Adds break and continue to the template engine.",
"jinja2.ext.debug": "A ``{% debug %}`` tag that dumps the available variables,",
"kamidana.extensions.NamingModuleExtension": "extension create from kamidana.additionals.naming",
"kamidana.extensions.ReaderModuleExtension": "extension create from kamidana.additionals.reader",
"kamidana.extensions.CookiecutterAdditionalModulesExtension": "activate additional modules, see context['cookiecutter']['_additional_modules'], created from your cookiecutter.json"
},
"additional_modules": {
"kamidana.additionals.env": "accessing environemt variable, via env()",
"kamidana.additionals.naming": "Naming helpers (e.g. snakecase, kebabcase, ... pluralize, singularize)",
"kamidana.additionals.reader": "Reading from other resources (e.g. read_from_file, read_from_command)"
}
}
```
--------------------------------
### Combine Multiple Additionals
Source: https://context7.com/podhmo/kamidana/llms.txt
Shows how to combine multiple additional modules when running Kamidana.
```bash
$ kamidana -a myfilters.py -a kamidana.additionals.naming template.j2
```
--------------------------------
### Using a Custom Rendering Driver via CLI
Source: https://context7.com/podhmo/kamidana/llms.txt
Specify a custom rendering driver using the `--driver` flag in the command line, referencing the module and class name.
```bash
$ kamidana --driver=custom_driver.py:UpperDriver --data data.yaml template.j2
```
--------------------------------
### Batch rendering with `kamidana-batch`
Source: https://context7.com/podhmo/kamidana/llms.txt
Renders multiple templates in a single pass using a JSON or YAML batch definition file. Specify the output directory with `--outdir`.
```bash
# Batch file: src/01batch.json
# [
# {"template": "src/00hello.j2", "data": {"name": "foo"}, "dst": "foo.hello"},
# {"template": "src/00hello.j2", "data": [{"name": "bar"}], "dst": "bar.hello"},
# {"template": "src/00hello.j2", "data": "me.json", "dst": "me.hello"}
# ]
$ kamidana-batch src/01batch.json --outdir=dst/01
# Produces: dst/01/foo.hello, dst/01/bar.hello, dst/01/me.hello
```
--------------------------------
### kamidana CLI Usage
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Displays the help message and available options for the kamidana command-line interface. Use this to understand all available arguments and configurations.
```console
usage: kamidana [-h] [--driver DRIVER] [--loader LOADER] [-d DATA]
[--logging {CRITICAL,FATAL,ERROR,WARN,WARNING,INFO,DEBUG,NOTSET}] [-a ADDITIONALS] [-e EXTENSION]
[-i {yaml,json,toml,csv,tsv,raw,env,md,markdown,spreadsheet}] [-o OUTPUT_FORMAT] [--dump-context]
[--list-info] [--debug] [--quiet] [--dst DST]
[template]
positional arguments:
template
options:
-h, --help show this help message and exit
--driver DRIVER default: kamidana.driver:Driver
--loader LOADER default: kamidana.loader:TemplateLoader
-d DATA, --data DATA support yaml, json, toml
--logging {CRITICAL,FATAL,ERROR,WARN,WARNING,INFO,DEBUG,NOTSET}
-a ADDITIONALS, --additionals ADDITIONALS
-e EXTENSION, --extension EXTENSION
-i {yaml,json,toml,csv,tsv,raw,env,md,markdown,spreadsheet}, --input-format {yaml,json,toml,csv,tsv,raw,env,md,markdown,spreadsheet}
-o OUTPUT_FORMAT, --output-format OUTPUT_FORMAT
--dump-context dumping loading data (used by jinja2 template)
--list-info listting information (for available extensions and additional modules)
--debug
--quiet
--dst DST
```
--------------------------------
### Run Kamidana with Custom Additionals
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Executes Kamidana with a specified Python file for additional modules and a YAML file for data, rendering a Jinja2 template.
```console
$ kamidana --additionals=examples/readme/src/01/additionals.py --data=examples/readme/src/01/data.yaml examples/readme/src/01/hello.jinja2
bye, world!!
```
--------------------------------
### Use Jinja2 'with', 'do', and 'loopcontrols' Extensions
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
A Jinja2 template demonstrating the usage of the 'with' statement for variable scoping, the 'do' tag for appending to lists, and 'loopcontrols' for break and continue within loops.
```jinja2
{# with with. with_ extension is used. #}
{%- with msg = "hello"%}
{{msg}}
{%- with msg = "world"%}
{{msg}}
{%- endwith %}
{{msg}}
{%- endwith %}
## counting
{#- with break and continue. loopcontrolls extension is used. #}
{%- for i in range(10) %}
{%- if i % 3 == 0 %}{% continue %} {% endif %}
{%- if i == 5 %}{% break %} {% endif %}
- {{i}}
{%- endfor %}
## do
{%- set xs = [] %}
{%- for i in range(10) %}
{%- do xs.append(i) %}
{%- endfor %}
{{xs}}
```
--------------------------------
### Write `kamidana` output to a file
Source: https://context7.com/podhmo/kamidana/llms.txt
Directs the rendered template output to a specified destination file using the `--dst` flag, instead of printing to standard output.
```bash
# Write output to a file instead of stdout
$ kamidana template.j2 --data data.yaml --dst output.txt
```
--------------------------------
### Use Jinja2 Extensions in Python API
Source: https://context7.com/podhmo/kamidana/llms.txt
Demonstrates using Kamidana's 'NamingModuleExtension' and 'ReaderModuleExtension' directly within Python code by passing them to the 'extensions' parameter of 'jinja2.Template' or 'jinja2.Environment'.
```python
from jinja2 import Template
# Use NamingModuleExtension directly in Python
tmpl = Template(
"{{ word|snakecase }} / {{ word|camelcase }} / {{ word|pluralize }}",
extensions=["kamidana.extensions.NamingModuleExtension"]
)
print(tmpl.render(word="fooBarBoo"))
# Output: foo_bar_boo / fooBarBoo / fooBarBoos
# Use ReaderModuleExtension
tmpl2 = Template(
'{{ "./notes.txt" | read_from_file }}',
extensions=["kamidana.extensions.ReaderModuleExtension"]
)
print(tmpl2.render())
```
--------------------------------
### Load custom additional modules with `kamidana`
Source: https://context7.com/podhmo/kamidana/llms.txt
Loads a custom Python module containing Jinja2 extensions using the `--additionals` flag. The module can be specified by path or name.
```bash
# Use the custom module
$ kamidana --additionals=myfilters.py --data data.yaml template.j2
# Template using the registered filter, global, and test:
# {{ greeting }}, {{ name|shout }}
# {% if name is long_string %}Name is long.{% endif %}
```
--------------------------------
### Dump Jinja2 Context with Merged Data Files
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Demonstrates merging contexts from multiple YAML files using the `--dump-context` flag in Kamidana. Later files override earlier ones.
```console
$ kamidana --dump-context --data=examples/readme/src/10/data.yaml --data=examples/readme/src/10/data2.yaml
{
"name": "foo",
"age": 21,
"friends": [
"bar",
"baz"
],
"template_filename": null
}
```
--------------------------------
### Batch rendering with output format conversion
Source: https://context7.com/podhmo/kamidana/llms.txt
Uses `kamidana-batch` to render templates and convert their output formats (e.g., raw to JSON or YAML) per entry in the batch definition.
```bash
# Batch with per-entry output format conversion (raw -> json, yaml)
# src/02batch.json:
# [
# {"template": "src/02person.json.j2", "data": {"name": "foo"}, "dst": "foo.json"},
# {"template": "src/02person.json.j2", "data": [{"name": "bar"}], "dst": "bar.json", "format": "json"},
# {"template": "src/02person.json.j2", "data": "me.json", "dst": "me.yaml", "format": "yaml"}
# ]
$ kamidana-batch src/02batch.json --outdir=dst/02
```
--------------------------------
### Custom Rendering Driver
Source: https://context7.com/podhmo/kamidana/llms.txt
The `--driver` flag accepts a `module:ClassName` reference to a custom subclass of `kamidana.driver.Driver`. This allows customizing the rendering process, such as transforming the output.
```APIDOC
## `--driver` — Custom rendering driver
The `--driver` flag accepts a `module:ClassName` reference to a custom subclass of `kamidana.driver.Driver` (which implements `kamidana.interfaces.IDriver`). The built-in drivers are `Driver` (standard rendering), `ContextDumpDriver` (dumps merged data as JSON), and `BatchCommandDriver` (used by `kamidana-batch`).
```python
# custom_driver.py — a driver that uppercases all output
from kamidana.driver import Driver
class UpperDriver(Driver):
def transform(self, t):
result = super().transform(t)
return result.upper()
```
```bash
$ kamidana --driver=custom_driver.py:UpperDriver --data data.yaml template.j2
```
```
--------------------------------
### Use Naming Filters in Jinja2
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Demonstrates the use of singularize, pluralize, snake_case, kebab-case, and camelCase filters provided by Kamidana's naming module.
```jinja2
{% set singular, plurals %}
- days|singularize -> {{'days'|singularize}}
- day|pluralize -> {{'day'|pluralize}}
- people|singularize -> {{'people'|singularize}}
- person|pluralize -> {{'person'|pluralize}}
to {snake_case, kebab-case, camelCase}
- fooBarBoo|snakecase -> {{'fooBarBoo'|snakecase}}
- fooBarBoo|kebabcase -> {{'fooBarBoo'|kebabcase}}
- foo_bar_boo|camelcase -> {{'foo_bar_boo'|camelcase}}
{% endset %}
{{ singular }}
```
--------------------------------
### Enable Jinja2 Extensions via CLI
Source: https://context7.com/podhmo/kamidana/llms.txt
Activates standard Jinja2 extensions like 'do', 'loopcontrols', and 'debug' using the '-e' flag. Kamidana's extensions can also be enabled by their full dotted path.
```bash
# Enable loopcontrols (break/continue) and do tag
$ kamidana -e do -e loopcontrols template.j2
# Enable NamingModuleExtension via -e flag
$ kamidana -e "kamidana.extensions.NamingModuleExtension" template.j2
```
```jinja2
{# template using loopcontrols and do #}
{%- set xs = [] %}
{%- for i in range(10) %}
{%- if i % 3 == 0 %}{% continue %}{% endif %}
{%- if i == 5 %}{% break %}{% endif %}
- {{ i }}
{%- do xs.append(i) %}
{%- endfor %}
collected: {{ xs }}
```
```text
# Output:
- 1
- 2
- 4
collected: [1, 2, 4]
```
--------------------------------
### Kamidana Gentle Error Messages: Missing Include
Source: https://context7.com/podhmo/kamidana/llms.txt
Kamidana reports missing template includes with clear messages, indicating the file and the line where the include failed. Use `--debug` for full tracebacks or `--quiet` to suppress errors.
```bash
# Missing included file
$ kamidana examples/readme/src/11/main.html.j2
------------------------------------------------------------
exception: kamidana._path.XTemplatePathNotFound
message: [Errno 2] No such file or directory: 'footer-404.html.j2'
where: examples/readme/src/11/main.html.j2
------------------------------------------------------------
examples/readme/src/11/main.html.j2:
2:
3: this is main contents
4:
-> 5: {% include "footer-404.html.j2" %}
```
--------------------------------
### kamidana Rendering with Stdin Data
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Demonstrates passing data to kamidana via stdin, overriding values from a data file. Ensure to specify the input format using `--input-format`.
```console
$ echo '{"nginx": {"logdir": "/tmp/logs/nginx"}}' | kamidana --input-format json examples/readme/src/00/nginx.jinja2 --data examples/readme/src/00/data.json
server {
listen 80;
server_name localhost;
root /var/www/project;
index index.htm;
access_log /tmp/logs/nginx/http.access.log combined;
error_log /tmp/logs/nginx/http.error.log;
}
```
--------------------------------
### Using a Custom Template Loader via CLI
Source: https://context7.com/podhmo/kamidana/llms.txt
Specify a custom template loader using the `--loader` flag in the command line, referencing the module and class name.
```bash
# Use the custom loader
$ kamidana --data=src/00/data.yaml \
--loader=src/00/loader.py:WithHeaderLoader \
src/00/use_customloader.py.j2
```
--------------------------------
### Run Kamidana with Jinja2 Extensions
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Executes Kamidana with the 'do' and 'loopcontrols' Jinja2 extensions enabled, rendering a template that utilizes advanced Jinja2 features.
```console
$ kamidana -e do -e loopcontrols examples/readme/src/02/use-extension.jinja2
hello
world
hello
## counting
- 1
- 2
- 4
## do
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
--------------------------------
### Kamidana File and Command Reader Filters
Source: https://context7.com/podhmo/kamidana/llms.txt
Enables 'read_from_file' and 'read_from_command' Jinja2 filters. Paths are relative to the template by default. Use the shorthand '-a reader' or the full path.
```bash
$ kamidana -a kamidana.additionals.reader src/02reader.jinja2
# or shorthand:
$ kamidana -a reader template.j2
```
```jinja2
{# template.j2 — reads a sibling file and runs a shell command #}
{# Read a file relative to this template's directory #}
{{ "./greeting.txt" | read_from_file }}
{# Read relative to the current working directory instead #}
{{ "src/greeting.txt" | read_from_file(relative_self=False) }}
{# Execute a shell command and embed its output #}
{{ "date +%Y-%m-%d" | read_from_command }}
{# Strip ANSI escape codes from command output #}
{{ "ls --color=always" | read_from_command | strip_ansi_escape_sequence }}
```
--------------------------------
### Batch rendering with shared global data
Source: https://context7.com/podhmo/kamidana/llms.txt
Combines per-entry data with shared global data loaded via the `--data` flag when using `kamidana-batch`.
```bash
# Supply shared global data in addition to per-entry data
$ kamidana-batch batch.json --data shared.yaml --outdir dist/
```
--------------------------------
### Basic `kamidana` rendering with JSON data
Source: https://context7.com/podhmo/kamidana/llms.txt
Renders a single Jinja2 template using data from a JSON file and outputs to stdout. Ensure the template and data file paths are correct.
```bash
# Basic rendering: nginx config from a JSON data file
# Template: examples/readme/src/00/nginx.jinja2
# Data: {"nginx": {"hostname": "localhost", "webroot": "/var/www/project", "logdir": "/var/log/nginx"}}
$ kamidana examples/readme/src/00/nginx.jinja2 --data examples/readme/src/00/data.json
server {
listen 80;
server_name localhost;
root /var/www/project;
index index.htm;
access_log /var/log/nginx/http.access.log combined;
error_log /var/log/nginx/http.error.log;
}
```
--------------------------------
### Provide Data for Templating
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
A YAML file containing data, specifically the 'name' variable, to be used in Kamidana templates.
```yaml
name: world
```
--------------------------------
### Data File for Templating (data.yaml)
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
A YAML file defining 'name', 'age', and 'friends' variables for use in Kamidana templates.
```yaml
name: foo
age: 20
friends:
- bar
- boo
```
--------------------------------
### Second Data File for Templating (data2.yaml)
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
A YAML file providing updated 'age' and 'friends' data, intended to be merged with other data sources.
```yaml
age: 21
friends:
- bar
- baz
```
--------------------------------
### Dump Jinja2 Context with Single Data File
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Uses the `--dump-context` flag with Kamidana to display the merged context from a single YAML data file.
```console
$ kamidana --dump-context --data=examples/readme/src/10/data.yaml
{
"name": "foo",
"age": 20,
"friends": [
"bar",
"boo"
],
"template_filename": null
}
```
--------------------------------
### Kamidana Naming Filters
Source: https://context7.com/podhmo/kamidana/llms.txt
Provides Jinja2 filters for case conversion (snake_case, kebab-case, camelCase, PascalCase) and English pluralization/singularization. Use the shorthand '-a naming' or the full path.
```bash
$ kamidana -a kamidana.additionals.naming template.j2
# or shorthand:
$ kamidana -a naming template.j2
```
```jinja2
{# template.j2 #}
- {{"fooBarBoo"|snakecase}} {# -> foo_bar_boo #}
- {{"fooBarBoo"|kebabcase}} {# -> foo-bar-boo #}
- {{"csv_reader"|camelcase}} {# -> csvReader #}
- {{"foo_bar"|pascalcase}} {# -> FooBar #}
- {{"days"|singularize}} {# -> day #}
- {{"person"|pluralize}} {# -> people #}
- {{"hello"|titleize}} {# -> Hello #}
```
```text
# Output:
- foo_bar_boo
- foo-bar-boo
- csvReader
- FooBar
- day
- people
- Hello
```
--------------------------------
### Custom Template Loader
Source: https://context7.com/podhmo/kamidana/llms.txt
The `--loader` flag allows specifying a custom template loader by referencing a `module:ClassName` that subclasses `kamidana.loader.TemplateLoader`. This enables pre-processing of template source before rendering.
```APIDOC
## `--loader` — Custom template loader
The `--loader` flag accepts a `module:ClassName` reference to a custom subclass of `kamidana.loader.TemplateLoader`. This allows pre-processing of template source before rendering (e.g. injecting a header, performing source transforms).
```python
# examples/customize/src/00/loader.py
from kamidana.loader import TemplateLoader
class WithHeaderLoader(TemplateLoader):
def load(self, filename):
buf = []
buf.append("# this file is auto generated by {!r}.\n\n".format(filename))
source, filename, _ = super().load(filename)
buf.append(source)
return "".join(buf), filename, None
```
```bash
# Use the custom loader
$ kamidana --data=src/00/data.yaml \
--loader=src/00/loader.py:WithHeaderLoader \
src/00/use_customloader.py.j2
# Output (dst/00/use_customloader.py):
# # this file is auto generated by 'src/00/use_customloader.py.j2'.
#
# def hello():
# return "hello world"
```
```
--------------------------------
### Dump merged data context with `kamidana`
Source: https://context7.com/podhmo/kamidana/llms.txt
Uses the `--dump-context` flag to display the merged data context as JSON without rendering any template. This is helpful for debugging data loading.
```bash
# Dump the merged data context without rendering a template
$ kamidana --dump-context --data=data.yaml
{
"name": "foo",
"age": 20,
"template_filename": null
}
```
--------------------------------
### Register Functions with Kamidana Decorators
Source: https://context7.com/podhmo/kamidana/llms.txt
Use decorators like `@as_filter`, `@as_global`, and `@as_test` to automatically register Python functions for use in templates. Functions can have multiple markers. `@as_globals_generator` can return a dictionary of global variables.
```python
from kamidana import as_filter, as_global, as_test, as_globals_generator
# Register as both a filter and a global function
@as_filter
@as_global
def env(envname, *, default=""):
import os
return os.environ.get(envname, default)
# Register as a Jinja2 test
@as_test
def even(value):
return value % 2 == 0
# Register a dict of globals via a generator function
@as_globals_generator
def generate_globals():
return {"app_name": "MyApp", "version": "1.0"}
# Collect all marked items from a module (used internally by TemplateLoader)
from kamidana import collect_marked_items
import mymodule
marked = collect_marked_items(mymodule)
# marked == {"filters": {"env": }, "globals": {"env": , "app_name": ..., "version": ...}, "tests": {"even": }}
```
--------------------------------
### Pipe JSON data to `kamidana` via stdin
Source: https://context7.com/podhmo/kamidana/llms.txt
Provides data to the `kamidana` command through standard input using the `--input-format json` flag. This is useful for dynamic data injection.
```bash
# Pipe JSON data via stdin
$ echo '{"nginx": {"logdir": "/tmp/logs/nginx"}}' \
| kamidana --input-format json examples/readme/src/00/nginx.jinja2 --data examples/readme/src/00/data.json
```
--------------------------------
### Custom Jinja2 filters, globals, and tests in Python
Source: https://context7.com/podhmo/kamidana/llms.txt
Defines custom Jinja2 extensions (filters, globals, tests) in a Python module using Kamidana decorators. These can then be loaded via the `--additionals` flag.
```python
# myfilters.py — a custom additional module
from kamidana import as_filter, as_globals_generator, as_test
@as_filter
def shout(value):
return value.upper() + "!!!"
@as_globals_generator
def generate_globals():
return {"greeting": "hello", "farewell": "bye"}
@as_test
def long_string(value, min_len=10):
return len(value) >= min_len
```
--------------------------------
### Define Custom Jinja2 Filters, Globals, and Tests
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
Python code defining a custom 'surprised' filter, 'daytime' and 'night' global variables, and a 'night' test function for use in Jinja2 templates.
```python
from kamidana import (
as_filter,
as_globals_generator,
as_test,
)
@as_filter
def surprised(v):
return "{}!!".format(v)
@as_globals_generator
def generate_globals():
return {"daytime": "hello", "night": "bye"}
@as_test
def night(hour):
return 19 <= hour or hour < 3
```
--------------------------------
### Handle Division by Zero Error
Source: https://github.com/podhmo/kamidana/blob/master/examples/basic/dst/03/runtime-error.html
This snippet shows a template that causes a division by zero error during rendering. The system will catch this and report it.
```html
{% include "./zero.div.html.j2" %}
```
--------------------------------
### Gentle Error Messages
Source: https://context7.com/podhmo/kamidana/llms.txt
Kamidana provides human-friendly error reports for template syntax errors, undefined variables, or missing includes, pointing to the exact line in the template. Use `--debug` for full tracebacks or `--quiet` to suppress output.
```APIDOC
## Gentle error messages
When a template has a syntax error, undefined variable, or a missing include, kamidana prints a human-friendly error report pointing to the exact offending line in the template, rather than a raw Python traceback. Use `--debug` to additionally print the full Python traceback, or `--quiet` to suppress all error output.
```bash
# A template with a broken expression: {{me|upper} (missing closing brace)
$ kamidana src/01invalid-syntax/broken.j2
# Output:
------------------------------------------------------------
exception: jinja2.exceptions.TemplateSyntaxError
message: unexpected '}'
where: src/01invalid-syntax/broken.j2
------------------------------------------------------------
src/01invalid-syntax/broken.j2:
1: Hello
2:
-> 3: This is {{me|upper}.
# Missing included file
$ kamidana examples/readme/src/11/main.html.j2
------------------------------------------------------------
exception: kamidana._path.XTemplatePathNotFound
message: [Errno 2] No such file or directory: 'footer-404.html.j2'
where: examples/readme/src/11/main.html.j2
------------------------------------------------------------
examples/readme/src/11/main.html.j2:
2:
3: this is main contents
4:
-> 5: {% include "footer-404.html.j2" %}
```
```
--------------------------------
### Kamidana Environment Variable Access
Source: https://context7.com/podhmo/kamidana/llms.txt
Provides an 'env' function to safely read environment variables with optional defaults. Usable as a global function or a filter. Use the shorthand '-a env' or the full path.
```bash
$ kamidana -a env template.j2
# or shorthand:
$ kamidana -a kamidana.additionals.env template.j2
```
```jinja2
{# template.j2 #}
{# Call as a global function #}
SHELL = {{ env("SHELL") }}
{# Call as a filter #}
HOME = {{ "HOME" | env }}
{# Provide a default value when the variable is missing #}
DB_URL = {{ env("DATABASE_URL", default="sqlite:///dev.db") }}
MISSING = {{ "NOT_SET" | env(default="") }}
```
```text
# Example output:
SHELL = /bin/bash
HOME = /home/user
DB_URL = sqlite:///dev.db
MISSING =
```
--------------------------------
### Kamidana Gentle Error Messages: Syntax Error
Source: https://context7.com/podhmo/kamidana/llms.txt
Kamidana provides human-friendly error reports for template issues like syntax errors, highlighting the exact line. Use `--debug` for full tracebacks or `--quiet` to suppress errors.
```bash
# A template with a broken expression: {{me|upper} (missing closing brace)
$ kamidana src/01invalid-syntax/broken.j2
# Output:
------------------------------------------------------------
exception: jinja2.exceptions.TemplateSyntaxError
message: unexpected '}'
where: src/01invalid-syntax/broken.j2
------------------------------------------------------------
src/01invalid-syntax/broken.j2:
1: Hello
2:
-> 3: This is {{me|upper}.
```
--------------------------------
### Include Missing Template
Source: https://github.com/podhmo/kamidana/blob/master/examples/basic/dst/04/main-error.html
This snippet shows an error when trying to include a template that does not exist. The rendering process stops and reports the error.
```html
{% include "missing-filter.html.j2" %}
```
--------------------------------
### Python API Decorators
Source: https://context7.com/podhmo/kamidana/llms.txt
Decorators like `as_filter`, `as_global`, `as_test`, and `as_globals_generator` from `kamidana` mark Python functions for automatic discovery and registration by `collect_marked_items()`.
```APIDOC
## Python API: `as_filter`, `as_global`, `as_test`, `as_globals_generator`
These decorators from `kamidana` mark Python functions so they are automatically discovered and registered by `collect_marked_items()` when a module is loaded as an additional. A function can carry multiple markers.
```python
from kamidana import as_filter, as_global, as_test, as_globals_generator
# Register as both a filter and a global function
@as_filter
@as_global
def env(envname, *, default=""):
import os
return os.environ.get(envname, default)
# Register as a Jinja2 test
@as_test
def even(value):
return value % 2 == 0
# Register a dict of globals via a generator function
@as_globals_generator
def generate_globals():
return {"app_name": "MyApp", "version": "1.0"}
# Collect all marked items from a module (used internally by TemplateLoader)
from kamidana import collect_marked_items
import mymodule
marked = collect_marked_items(mymodule)
# marked == {"filters": {"env": }, "globals": {"env": , "app_name": ..., "version": ...}, "tests": {"even": }}
```
```
--------------------------------
### Merge multiple data files with `kamidana`
Source: https://context7.com/podhmo/kamidana/llms.txt
Merges data from multiple YAML files, where later files override earlier ones. This is useful for layering configurations.
```bash
# Merge two data files (second overrides first)
$ kamidana --data=base.yaml --data=override.yaml template.j2
```
--------------------------------
### Conditional Rendering in Jinja2 Template
Source: https://github.com/podhmo/kamidana/blob/master/README.rst
A Jinja2 template that conditionally renders messages based on whether the hour is considered 'night' or 'daytime', using a custom test.
```jinja2
{% if 19 is night %}
{{night}}, {{name|surprised}}
{% else %}
{{daytime}}, {{name|surprised}}
{% endif %}
```
--------------------------------
### Python Filter Exception
Source: https://github.com/podhmo/kamidana/blob/master/examples/basic/dst/04/main-error.html
This Python code defines a custom filter that intentionally raises an exception. This exception is then caught during template rendering.
```python
def use(x):
return oops(x)
def oops(x):
raise Exception("oops {}".format(x))
```
--------------------------------
### Invalid Filter Usage in Jinja Template
Source: https://github.com/podhmo/kamidana/blob/master/examples/basic/dst/04/invalid-filter.html
This Jinja template attempts to use a filter named 'use' which is not defined, causing an exception during rendering. Ensure all filters are correctly defined and imported.
```html
{% for i in range(10) %}
- {{i}} {{ "foo" | use }}
{% endfor %}
```
--------------------------------
### Template with Missing Filter
Source: https://github.com/podhmo/kamidana/blob/master/examples/basic/dst/04/missing-filter.html
This Jinja2 template attempts to use the 'upper' filter and a non-existent 'downer' filter. The 'downer' filter will cause a TemplateAssertionError.
```html
Missing Filter Example
{{ "abc" | upper }}
{{ "ABC" | downer }}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.