DEV Community

Discussion on: Intro to PYJSX

Collapse
 
k0msenapati profile image
K Om Senapati

Wow its so cool

But is it better than Jinja2 ?
That can be setup easily with fastapi or flask

Collapse
 
ddebajyati profile image
Debajyati Dey • Edited

Well actually Jinja really serves its purpose greatly. That being said, it is a templating engine for python.

Jinja is generally static, (HTML rendered before delivery). While JSX is dynamic and is loved by devs mostly for its component-based reusability, nesting and the ability of easily passing props for dynamic behavior.

The best way is to use the best of both worlds. 

As in the end, we are converting PyJSX into strings currently for rendering as html, we will be able to use them directly in flask routes. What we can do is break our whole UI into reusable components and then serve them as html when sending via response in flask routes.

A Quick Example for you if my explanation above was messy (sorry 🥲😅😅🥲) -

PyJSX with Flask

With PyJSX, you define your components in Python files (often with a .px extension, though not strictly required for simple cases if transpiled correctly). The output of a PyJSX component is of JSX type which can be formatted in fstrings, which Flask can directly return.

First, define a PyJSX component. You would typically save this in a file, for example, component.px -

# coding: jsx
from pyjsx import jsx, JSX

def HomePage(user_name, items) -> JSX:
    list_items = [<li>{item}</li> for item in items]
    return (
        <>
            <h1>PyJSX Home Page</h1>
            <p>Welcome, {user_name} from PyJSX!</p>
            <p>Here are your items:</p>
            <ul>{list_items}</ul>
        </>
    )
Enter fullscreen mode Exit fullscreen mode

Then, in your Flask application (app.py), you would import and use these components:

from flask import Flask
from pyjsx import auto_setup
from component import HomePage

app = Flask(__name__)

@app.route('/')
def home_pyjsx():
    # Render the PyJSX component to a string
    rendered_html = HomePage(user_name="KOmSenpati", items=["Pen", "Paper", "Laptop"])
    print(rendered_html)
    return f'{rendered_html}', {'Content-Type': 'text/html'}

if __name__ == '__main__':
    app.run()
Enter fullscreen mode Exit fullscreen mode

See it works perfectly fine -

Running the flask server