Coder Social home page Coder Social logo

templa's Introduction

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

Docs

Templa Documentation

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()

templa's People

Contributors

yuxki avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.