From 40378554e1bff8371434fce1dee297fa45144ba5 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Wed, 4 Nov 2026 00:04:21 +0100 Subject: [PATCH 1/8] fix typos in README --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 84d7669..0400c82 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Cuddly -Generate HTML and PDF from KDL structed data. +Generate HTML and PDF from KDL structured data. ## Installation @@ -85,7 +85,7 @@ my_node { ```jinja {% for node in my_node.other_node %} {{ node.value }} -{% endofr %} +{% endfor %} ``` renders to @@ -133,7 +133,7 @@ menu "Midnight meal" price="10 €" {

{{ value }}

Price
-
{{ attributes.prices }}
+
{{ attributes.price }}
@@ -144,7 +144,7 @@ menu "Midnight meal" price="10 €" {
-
{{ attribute.name }}
+
{{ attributes.name }}
{{ value }}
-- 2.56.1 From 7ed2fdaee4f4b095df66c67a27a6e0123cbc6784 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Wed, 4 Nov 2026 23:21:26 +0100 Subject: [PATCH 2/8] =?UTF-8?q?don=E2=80=99t=20crash=20and=20return=20None?= =?UTF-8?q?=20when=20testing=20a=20property=20that=20don=E2=80=99t=20exist?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit for example in: `{% if foo.bar %}{{ foo.bar }}{% endif %}` --- cuddly/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cuddly/__init__.py b/cuddly/__init__.py index 3fa031f..0c43303 100644 --- a/cuddly/__init__.py +++ b/cuddly/__init__.py @@ -71,8 +71,7 @@ class CuddlyNode(object): return getattr(self.inner, 'name', None) def __getattr__(self, name): - children = self.children[name] - return children + return self.children.get(name) def __str__(self): return str(self.value) -- 2.56.1 From 0ecf731df87933d1d9a6eb9af47f906295efde70 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Wed, 4 Nov 2026 23:31:15 +0100 Subject: [PATCH 3/8] clean and re-order imports, and code style changes --- cuddly/__init__.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/cuddly/__init__.py b/cuddly/__init__.py index 0c43303..1d58df7 100644 --- a/cuddly/__init__.py +++ b/cuddly/__init__.py @@ -1,14 +1,15 @@ -import sys import pathlib from urllib.parse import urlparse -import kdl import click +import kdl from bs4 import BeautifulSoup from bs4.element import Tag from jinja2 import Environment +from weasyprint import HTML -class CuddlyMaybeList(object): + +class CuddlyMaybeList: """ If the given list is only one item behave like a proxy to that item. """ @@ -36,7 +37,7 @@ class CuddlyMaybeList(object): def __getitem__(self, key): return self.inner[key] -class CuddlyNode(object): +class CuddlyNode: """ Common interface to Document and Node. Provide helper method to render to HTMl. @@ -89,7 +90,7 @@ class CuddlyNode(object): return template.render(variables) -class RenderNode(object): +class RenderNode: def __init__(self, components, env): self.components = components self.env = env @@ -125,12 +126,13 @@ def main(template, input, output): with open(template_path) as template_file: template_html = BeautifulSoup(template_file.read(), features="html.parser") components = template_html.components.extract() - components = [element for element in components.children if isinstance(element, Tag)] + components = [ + element for element in components.children if isinstance(element, Tag) + ] template_string = template_html.decode() components = { - component.name: component.decode_contents().strip() - for component in components + component.name: component.decode_contents().strip() for component in components } with open(input) as input_file: -- 2.56.1 From fcc05b233c36ea254c59f8d52bcc04cded89cfe9 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Sun, 8 Nov 2026 02:15:45 +0100 Subject: [PATCH 4/8] add short options and possibility to use several --output --- README.md | 6 ++++++ cuddly/__init__.py | 25 +++++++++++++------------ 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 0400c82..8f2d1ef 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,12 @@ Generating a HTML file env/bin/cuddly --template samples/cv/cv.template.html --input samples/cv.kdl --output samples/cv.html ``` +Generating both at the same time, with short options: + +``` +env/bin/cuddly -t samples/cv/cv.template.html -i samples/cv.kdl -o samples/cv.pdf -o samples/cv.html +``` + ### Template usage The template language used is [Jinja](https://jinja.palletsprojects.com/en/3.0.x/), source template need to be a single HTML template file. diff --git a/cuddly/__init__.py b/cuddly/__init__.py index 1d58df7..e068424 100644 --- a/cuddly/__init__.py +++ b/cuddly/__init__.py @@ -115,10 +115,10 @@ def stripscheme(url): return url[scheme_len:] @click.command() -@click.option('--template', help="Path to a template file") -@click.option('--input', help="Path to a KDL file") -@click.option('--output', help="Output file") -def main(template, input, output): +@click.option('-t', '--template', help="Path to a template file") +@click.option('-i', '--input', help="Path to a KDL file") +@click.option('-o', '--output', 'outputs', help="Output file", multiple=True) +def main(template, input, outputs): """ Template a file using a KDL input """ @@ -145,11 +145,12 @@ def main(template, input, output): output_html = input_node.render(template) - if output.endswith('.pdf'): - from weasyprint import HTML, default_url_fetcher - base_dir = pathlib.Path(template_path).absolute().parent - HTML(string=output_html, base_url=f'file://{base_dir}/').write_pdf(output, pdf_variant='pdf/ua-1') - - else: - with open(output, 'w') as output_file: - output_file.write(output_html) + for output in outputs: + if output.endswith('.pdf'): + base_dir = pathlib.Path(template_path).absolute().parent + HTML(string=output_html, base_url=f'file://{base_dir}/').write_pdf( + output, pdf_variant='pdf/ua-1' + ) + else: + with open(output, 'w') as output_file: + output_file.write(output_html) -- 2.56.1 From 23150fe6f7d688a9a363f02b4bbca58413628026 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Sun, 8 Nov 2026 02:19:10 +0100 Subject: [PATCH 5/8] improve an error message --- cuddly/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cuddly/__init__.py b/cuddly/__init__.py index e068424..aea4108 100644 --- a/cuddly/__init__.py +++ b/cuddly/__init__.py @@ -97,7 +97,10 @@ class RenderNode: def __call__(self, node): if isinstance(node, CuddlyMaybeList) and len(node) > 1: - raise Exception(f'Render filter must called be on single node, not list, got {type(node)}') + raise Exception( + f'Cannot use `render` filter on list `{type(node)}`, ' + + 'use it on a single node instead' + ) if node.name in self.components: template = self.env.from_string(self.components[node.name]) -- 2.56.1 From e0efccbfd60daa75737d178ab81ec1cbf64a1482 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Sun, 8 Nov 2026 18:47:36 +0100 Subject: [PATCH 6/8] add support for KDL 2.0 (upgrade kde-py) --- cuddly/__init__.py | 41 ++++++++++++++++++----------------------- pyproject.toml | 2 +- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/cuddly/__init__.py b/cuddly/__init__.py index aea4108..8881b8c 100644 --- a/cuddly/__init__.py +++ b/cuddly/__init__.py @@ -43,33 +43,28 @@ class CuddlyNode: Provide helper method to render to HTMl. Allow access to children nodes like object properties. """ - def __init__(self, inner): - self.inner = inner - self.children = {} - for node in self.inner.nodes: - self.children.setdefault(node.name, []) - self.children[node.name].append(CuddlyNode(node)) + def __init__(self, kdl_node): + self.name = getattr(kdl_node, 'name', None) - self.children = {name: CuddlyMaybeList(nodes) for name, nodes in self.children.items()} + self.values = [] + self.attributes = {} + for entry in getattr(kdl_node, 'entries', []): + if entry[0] is None: + self.values.append(entry[1]) + else: + self.attributes[entry[0]] = entry[1] + + children = {} + for node in kdl_node.nodes: + children.setdefault(node.name, []).append(CuddlyNode(node)) + + self.children = { + name: CuddlyMaybeList(nodes) for name, nodes in children.items() + } @property def value(self): - if args := getattr(self.inner, 'args', None): - return args[0] - else: - return None - - @property - def values(self): - return getattr(self.inner, 'args', []) - - @property - def attributes(self): - return getattr(self.inner, 'props', {}) - - @property - def name(self): - return getattr(self.inner, 'name', None) + return next(iter(self.values), None) def __getattr__(self, name): return self.children.get(name) diff --git a/pyproject.toml b/pyproject.toml index 14f825c..9a9541d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" version = "0.1" name = "cuddly" dependencies = [ - "kdl-py==1.2.0", + "kdl-py @ git+https://github.com/tabatkins/kdlpy@d9a220762fb9f55e4f59296256221084c26f54da", "beautifulsoup4==4.12.3", "Jinja2==3.1.3", "click==8.1.7", -- 2.56.1 From d9713da6fddb34e62ecf6d4a96a4a9b234fae1f0 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Sun, 8 Nov 2026 18:49:08 +0100 Subject: [PATCH 7/8] update and improve documentation --- README.md | 69 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 38 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 8f2d1ef..fe441f7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Cuddly -Generate HTML and PDF from KDL structured data. +Generate HTML and PDF files, with HTML and Jinja templates, from KDL structured data. ## Installation @@ -11,7 +11,7 @@ python -m venv env env/bin/pip install . ``` -## Usage +## Basic Usage ### Example @@ -32,15 +32,25 @@ Generating both at the same time, with short options: env/bin/cuddly -t samples/cv/cv.template.html -i samples/cv.kdl -o samples/cv.pdf -o samples/cv.html ``` -### Template usage +### Samples -The template language used is [Jinja](https://jinja.palletsprojects.com/en/3.0.x/), source template need to be a single HTML template file. +* `samples/cv/cv.template.html`: Template to generate a CV, see `samples/cv.kdl` for the input data. +* `samples/facture/facture.template.html`: Template to generate a French invoice, see `samples/facture.kdl` for the input data. -#### Base URL -When generating the PDF the base URL is set to the source template directory. All relative links to other resources (for example CSS and images) must be relative to that directory. +## Template usage -#### Accessing nodes values and attributes +The source template need to be a single HTML template file. + +- The template language is [Jinja](https://jinja.palletsprojects.com/en/3.0.x/). +- For PDFs, the resulting HTML is run through [Weasyprint](https://weasyprint.org/). +- The data language is [KDL](https://kdl.dev/) (2.0.0). + +### Base URL + +When generating a PDF, the base URL is set to the source template directory. All relative links to other resources (for example CSS and images) must be relative to that directory. + +### Accessing nodes values and attributes Nodes are available as global variables in the template. The rendered value of a node is the first value that has been assigned to the node. This value can also be accessed using the `value` property. The list of values can be accessed using the `values` property. @@ -62,7 +72,23 @@ something something, other thing ``` -Accessing children nodes can be done using properties of the children names. +Attributes of a node can be accessed through the `attributes` property: + +```kdl +my_node version=42 "something" +``` + +```jinja +{{ my_node.attributes.version }} +``` +renders to +``` +42 +``` + +### Accessing children nodes + +Children nodes can be accessed using the children names. ```kdl my_node { @@ -79,7 +105,7 @@ renders to test ``` -If a node has multiple children of a same node type, then directly accessing the children properties will fail, a loop will be needed. Note that, on the other hand, looping on the children always work, even if there is only one child of the given type. +If a node has multiple children of a same node type, you’ll need to use a loop (directly accessing the children properties will fail). Note that, on the other hand, looping on the children always work, even if there is only one child of the given type. ```kdl my_node { @@ -101,25 +127,11 @@ first second ``` -Attributes of a node can be accessed through the `attributes` property: +### Using components to template nodes -```kdl -my_node version=42 "something" -``` +You can define node specific templates inside the `components` tag in the HTML template file. Nodes can then be rendered using those micro-templates using the `render` filter. -```jinja -{{ my_node.attributes.version }} -``` -renders to -``` -42 -``` - -#### Templating nodes - -Node specific templates can be defined in the `components` element in the HTML template file. Nodes can then be rendered using those micro-templates using the `render` filter. - -The context of the micro-template is the node being rendered. As such, children and properties of that node are in the global scope. +The context of the micro-template is the node being rendered. As such, children and properties (`value`, `values`, `attributes`) of that node are in the global scope. ```kdl menu "Midnight meal" price="10 €" { @@ -159,8 +171,3 @@ menu "Midnight meal" price="10 €" { {{ menu | render }} ``` - -## Samples - -* `samples/cv/cv.template.html`: Template to generate a CV, see `samples/cv.kdl` for the input data. -* `samples/facture/facture.template.html`: Template to generate a French invoice, see `samples/facture.kdl` for the input data. -- 2.56.1 From 67f4ec86677495564fd8633ede36d70fd8333ef2 Mon Sep 17 00:00:00 2001 From: ariasuni Date: Sun, 8 Nov 2026 19:47:33 +0100 Subject: [PATCH 8/8] update .gitignore (remove useless stuff, add .pdf and .html files) --- .gitignore | 163 ++--------------------------------------------------- 1 file changed, 5 insertions(+), 158 deletions(-) diff --git a/.gitignore b/.gitignore index 5d381cc..42a45fc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,162 +1,9 @@ -# ---> Python -# Byte-compiled / optimized / DLL files +# Python __pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ +build *.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -#pdm.lock -# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it -# in version control. -# https://pdm.fming.dev/#use-with-ide -.pdm.toml - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ +# Generated files +**/*.html +**/*.pdf -- 2.56.1