aroberge / ideas

Easy creation of custom import hooks to experiment on alternatives to Python's syntax; see https://aroberge.github.io/ideas/docs/html/
Other
76 stars 5 forks source link

Add example embedding HTML in Python. #40

Closed tomkcook closed 1 year ago

tomkcook commented 1 year ago

I built this for a side project I'm working on and thought it made a good, relatively complex example of what you can do with ideas so wanted to offer it back as an example.

This transform lets you embed HTML in Python code in a way that is fairly similar to JSX in JavaScript. HTML is surrounded by a new pair of operators, both of them sad faces - :( and ):. These delimiters must contain exactly one top-level HTML element but that can then contain as many nested elements as you like. You need to provide a function called el which constructs an HTML element. Element attributes can have Python values using the {expression} notation from JSX and you can also embed Python values in text elements using the same notation.

The unit tests cover 89% of the statements in the transform file and give good examples of what can be done, but briefly the source looks like this:

def el(name: str, attrs: dict, *children):
    pass

def get_html(title: str, div_class: str):
    return :(
        <div class={div_class}>
            <h1>Title: {title}</h1>
        </div>
    ):
aroberge commented 1 year ago

Thank you for this example!