Skip to main content

Building system using Jinja2 templates for your code.

Project description

pre-commit Run Tests Documentation Status Coverage Status Code style: black Stable Version Python Versions

templa

Templa is a Python library that offers a flexible and typed building system using Jinja2 templates for your code. It allows you to easily render, parse, process, and build. The following are the assumed build processes in Templa:

  • Define the required context with dataclass for rendering a Jinja2 formatted template.
  • Render the template with Jinja2 library using the provided context.
  • Extract relevant information and elements from the rendered template for further processing.
  • Perform necessary processing on the parsed rendered template.
  • Utilize the processed rendered template to generate desired outputs or objects.

Installation

$ pip install templa

Example

from dataclasses import dataclass
from typing import List
from typing import Optional

import jinja2
import yaml

from templa.builder import Builder
from templa.config import Config
from templa.config import ConfigData


def parse_rendered_template_yaml_stub(rendered_str: str) -> Optional[List[str]]:
    parsed_rendered_template = yaml.safe_load(rendered_str)
    assert (
        isinstance(parsed_rendered_template, list) or parsed_rendered_template is None
    )
    return parsed_rendered_template


def build_parsed_rendered_template_yaml_stub(
    parsed_rendered_template: Optional[List[str]],
) -> Optional[str]:
    built = yaml.dump(parsed_rendered_template, Dumper=yaml.SafeDumper)
    assert isinstance(built, str)
    return built


class SampleTemplateGetter:
    def get_template(self) -> jinja2.Template:
        environment = jinja2.Environment(
            loader=jinja2.DictLoader(
                {"template.txt": "---\n- {{ foo }}\n- {{ bar }}\n- {{ zoo }}"}
            )
        )
        return environment.get_template("template.txt")


@dataclass(frozen=True)
class SampleConfigData(ConfigData):
    foo: str
    bar: str


class SampleBuilder(Builder[List[str], str]):
    def __init__(
        self,
    ) -> None:
        super().__init__(
            config=Config[SampleConfigData]({"foo": "FOO", "bar": 5}, SampleConfigData),
            template_getter=SampleTemplateGetter(),
            parse_rendered_template=parse_rendered_template_yaml_stub,
            build_processed=build_parsed_rendered_template_yaml_stub,
        )

    def _build(self, processed: Optional[List[str]]) -> Optional[str]:
        if processed is not None:
            processed[2] = "ZOO_Updated"
        return super()._build(processed)


def build_sample_template() -> None:
    builder = SampleBuilder()
    initialized_target = builder.init_builder_target()

    # It will be typing error because the builder variable is in a
    # state of an unfinished type before the build process is
    # completed, causing a type error.
    # builder.build(initialized_target)
    # ->  Argument 1 to "build" of "Builder" has incompatible type
    #     "BuilderTargetInitialized"; expected "BuilderTargetProcessed"  [arg-type]

    processed_target = builder.process_template(initialized_target)
    built_target = builder.build(processed_target)
    print(builder.fetch_built(built_target))


if __name__ == "__main__":
    build_sample_template()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

templa-1.0.0.tar.gz (8.1 kB view details)

Uploaded Source

Built Distribution

templa-1.0.0-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file templa-1.0.0.tar.gz.

File metadata

  • Download URL: templa-1.0.0.tar.gz
  • Upload date:
  • Size: 8.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.1 CPython/3.11.3

File hashes

Hashes for templa-1.0.0.tar.gz
Algorithm Hash digest
SHA256 74248536de70b12574abd63035015860e06230e2053326d010ead2a96c637b8b
MD5 b465d8eb243b5256dc8f6d07d708b858
BLAKE2b-256 6674bcf535be56f1484553f12adfb9a25f1096ac7cb67553433477f15e99a50c

See more details on using hashes here.

File details

Details for the file templa-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: templa-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 8.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.1 CPython/3.11.3

File hashes

Hashes for templa-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 579f034983c0ce2dfe94dc49b2d76c9c9cdd2f4af21be5445d4527f7815395a4
MD5 cfc2440e13996eae3464aa3b3bc2ecb4
BLAKE2b-256 39aabe255539cf0a3f0b5de06088c55b21d27c46cf315a1f5251da2bbc240663

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page