Skip to content

Commit

Permalink
WIP Jinja support.
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaheedHaque committed Oct 9, 2023
1 parent 6f79c4c commit 54906cf
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/reactpy_django/templatetags/jinja.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Copyright © 2023 Innovatie Ltd. All rights reserved.
"""
Jinja support.
"""
import typing as t

from jinja2 import pass_context
from jinja2.ext import Extension
from jinja2.runtime import Context, Undefined


class ReactPyExtension(Extension):
"""
Jinja has more expressive power than core Django's templates, and can
directly handle expansions such as:
{{ component(*args, **kwargs) }}
"""
#
# Therefore, there is no new tag to parse().
#
tags = {}

def __init__(self, environment):
super().__init__(environment)
#
# All we need is to add global "component" to the environment.
#
environment.globals["component"] = self._component

@pass_context
def _component(self, __context: Context, implementation: str, *args: t.Any,
**kwargs: t.Any) -> t.Union[t.Any, Undefined]:
"""
This method is used to embed an existing ReactPy component into your
Jinja2 template.
Args:
implementation: String of the fully qualified name of a component.
*args: The component's positional arguments.
**kwargs: The component's keyword arguments.
Returns:
Whatever the components returns.
"""
module, name = implementation.rsplit('.', 1)
component = getattr(__import__(module, None, None, [name]), name)
template_args = component(*args, **kwargs).render()
#
# TODO: template_args looks like this:
#
# {'tagName': 'h1', 'children': ['Hello World!']}
#
# and need to be run through the Django template in
# templates/reactpy/component.html, or equivalent.
#
return template_args

0 comments on commit 54906cf

Please sign in to comment.