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?