At our company we love to write django driven applications and we also love to use react. Recently we thought about writing a component based templating engine for python where templates can be written as react-like components using JSX.
Ideally it should be possible to embed JSX into the python code so that you can write components like this:
In header.pyx:
import PyReact
from my_awsome_project.components import Logo, Link
def Header(context):
page_title = context.get('page_title')
links = context.get('links')
return (
<div>
<Logo />
{page_title}
<ul>
{[<Link href={link.url}>{link.title}</Link> for link in links]}
</ul>
</div>
)
This would of course require to transpile the file first to get valid python code. It would transpile to something somewhat similar as that:
import PyReact
from my_awsome_project.components import Logo, Link
def Header(context):
page_title = context.get('page_title')
links = context.get('links')
return (
PyReact.createComponent('div', context, [
PyReact.createComponent(Logo),
page_title,
PyReact.createComponent('ul', context, [
[
PyReact.createComponent(Link, {'href': link.url}, link.title)
for link in links
]
]),
])
)
The question is: How would I approach writing such a transpiler?
Also we thought about instead of embedding JSX directly into the python code directly we could return a string containing the JSX that gets parsed independently. Would that be a better/easier approach?
Actually, this is possible. There is a library called: packed[1]. But it seems that the project has been abandoned, last commit was 5 years ago. To quote its readme:
@packed
def tag(self):
share = get_share_link()
return <a href={share}>Share on internet</a>
# to:
@packed
def tag(self):
share = get_share_link()
return Elem(
'a',
{
'href': share,
},
'Share on internet',
)
Anyway, if you are looking for a new way of rendering html on the server side by python other than jinja templates, take a look at htmx, it seems promising.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With